javascript事件绑定1-模拟jquery可爱的东西
1、给对象添加事件attachEvent(兼容IE,不兼容ff、chrome)
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>事件绑定</title> <script type="text/javascript"> window.onload = function () { var btn1 = document.getElementById('btn1'); //attachEvent给对象绑定事件,兼容IE,不兼容FF,chrome //第一个参数是绑定的事件每次,第二个参数是function btn1.attachEvent("onclick", function () { alert("我在IE上蹦蹦跳!"); }); } </script> </head> <body> <input type="button" value="绑定" id="btn1" /> </body> </html>
不兼容FF、chrome
2、兼容FF、chrome(IE9及以上也兼容)
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>事件绑定</title> <script type="text/javascript"> window.onload = function () { var btn1 = document.getElementById('btn1'); //#region 兼容IE // btn1.attachEvent("onclick", function () { // alert("我是IE蹦蹦跳"); // }); //#endregion //addEventListener(事件名称但是没有"on"前缀,绑定的function,是否进行捕获(一般是false)) btn1.addEventListener("click", function () { alert("我是FF、Chrome蹦蹦跳,IE9及以上也兼容"); },false); } </script> </head> <body> <input type="button" value="绑定" id="btn1" /> </body> </html>
3、兼容FF、chrome、ie
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>事件绑定</title> <script type="text/javascript"> window.onload = function () { var btn1 = document.getElementById('btn1'); if (btn1.attachEvent) {//如果是IE btn1.attachEvent("onclick", function () { alert("我是IE蹦蹦跳"); }); } else{//如果是非IE btn1.addEventListener("click", function () { alert("我是FF、Chrome蹦蹦跳,IE9及以上也兼容"); }, false); } } </script> </head> <body> <input type="button" value="绑定" id="btn1" /> </body> </html>
4、封装起来
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>事件绑定</title> <script type="text/javascript"> window.onload = function () { var btn1 = document.getElementById('btn1'); addEvent(btn1, 'click', function () { alert("我居然被包养了!!!"); }); addEvent(btn1, 'click', function () { alert("我居然被封装了!!!"); }); } //obj:绑定的对象,eventName:事件名称,fn:函数 function addEvent(obj, eventName, fn) { if (obj.attachEvent) { obj.attachEvent('on' + eventName, fn); } else { obj.addEventListener(eventName, fn, false); } } </script>
5、小小模拟jquery
$(function () {
alert("sss");
});
function $(paramArgs) {
return new myQuery(paramArgs);
}
function myQuery(paramArgs) {
var argType = typeof paramArgs;
switch (argType) {
case "function":
addEvent(window, "load", paramArgs);
break;
}
}
6、事件绑定应用:
执行结果
生活没有输赢,不要在乎别人如何评价你,开心就好。
QQ群:158138959