JS动态添加事件

来源:互联网 发布:扎古2.0知乎 编辑:程序博客网 时间:2024/04/30 18:02
方法一、setAttribute
var obj = document.getElementById("obj");
obj.setAttribute("onclick", "javascript:alert('测试');");
但是IE不支持用 setAttribute 设置某些属性,包括对象属性、集合属性、事件属性,也就是说用 setAttribute 设置 style、onclick、onmouseover 这些属性在 IE 中是行不通的。

方法二、用 attachEvent 和 addEventListener
IE 支持 attachEventobject.attachEvent(event,function),例如:
obj.attachEvent("onclick", Foo);function Foo(){    alert("测试");}
或者写成 obj.attachEvent("onclick", function(){alert("测试");});
其它浏览器支持 addEventListener,element.addEventListener(type,listener,useCapture,
obj.addEventListener("click", Foo, false);function Foo(){    alert("测试");}
同样也可写在一起obj.addEventListener("click", function(){alert("测试");}, false);
注意 attachEvent 的事件带 on,如 onclick,而 addEventListener 不带 on,如 click。
考虑兼容性:if (window.attachEvent)//兼容IE{    //IE 的事件代码}else{    //其它浏览器的事件代码}

上面有两种添加事件的方法,为了同一添加事件的方法,我们不得不再重新写一个通用的添加事件函数:

版本一:

function addEvent(elm, evType, fn, useCapture) {if (elm.addEventListener) {elm.addEventListener(evType, fn, useCapture);//DOM2.0return true;}else if (elm.attachEvent) {var r = elm.attachEvent(‘on‘ + evType, fn);//IE5+return r;}else {elm['on' + evType] = fn;//DOM 0}}

HTML5工作组的版本:
var addEvent=(function(){if(document.addEventListener){return function(el,type,fn){if(el.length){for(var i=0;i<el.length;i++){addEvent(el[i],type,fn);}}else{el.addEventListener(type,fn,false);}};}else{return function(el,type,fn){if(el.length){for(var i=0;i<el.length;i++){addEvent(el[i],type,fn);}}else{el.attachEvent(‘on‘+type,function(){return fn.call(el,window.event);});}};}})();

方法三、事件 = 函数

例:obj.onclick = Foo;
这种绑定事件的方式,兼容主流浏览器,但如果一个元素上添加多次同一事件呢?
1obj.onclick=method1;
2obj.onclick=method2;
3obj.onclick=method3;

如果这样写,那么只有最后绑定的事件,这里是method3会被执行,此时应该用方法二的方法进行事件的绑定



区别IE6、IE7、IE8之间的方法:

var isIE=!!window.ActiveXObject;var isIE6=isIE&&!window.XMLHttpRequest;var isIE8=isIE&&!!document.documentMode;var isIE7=isIE&&!isIE6&&!isIE8;if (isIE){  if (isIE6){    alert(”ie6″);  }else if (isIE8){    alert(”ie8″);  }else if (isIE7){    alert(”ie7″);  }}



原创粉丝点击