js事件监听是学习js过程中必然要学习和掌握的。下面是js事件监听的代码
function addEventHandler(target, type, func) { if (target.addEventListener) target.addEventListener(type, func, false); else if (target.attachEvent) target.attachEvent("on" + type, func); else target["on" + type] = func; }
有人问我,为什么我要用事件监听呢?因为我在target后面加一个.onclick或者.onmouseover 等等的事
件,各个浏览器都是完全兼容的啊。下面几点就说明我们为什么要使用事件监听器。
第一:当同一个对象使用.onclick的写法触发多个方法的时候,后一个方法会把前一个方法覆盖掉,也就
是说,在对象的onclick事件发生时,只会执行最后绑定的方法。而是用事件监听则不会有覆盖的现象,
每个绑定的事件都会被执行。但是IE家族先执行后绑定的方法,也就是逆绑定顺序执行方法,其他浏览器
按绑定次数顺序执行方法。
第二:也是最重要的一点,采用事件监听给对象绑定方法后,可以解除相应的绑定,写法如下
第二:也是最重要的一点,采用事件监听给对象绑定方法后,可以解除相应的绑定,写法如下 function removeEventHandler(target, type, func) { if (target.removeEventListener) target.removeEventListener(type, func, false); else if (target.detachEvent) target.detachEvent("on" + type, func); else delete target["on" + type]; }
第三:解除绑定事件的时候一定要用函数的句柄,把整个函数写上是无法解除绑定的。看实例: 错误的写法: addEventHandler(Button1, "click", function() { alert("3"); } ); removeEventHandler(Button1, "click", function() { alert("3"); }); 正确的写法: function test(){alert("3");} addEventHandler(Button1, "click", test ); removeEventHandler(Button1, "click", test); 下面为整个HTML代码示例: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1.0-Transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Javascript事件监听</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> </head> <body> <button id="Button1">测试</button> <script type="text/javascript"> function addEventHandler(target, type, func) { if (target.addEventListener) target.addEventListener(type, func, false); else if (target.attachEvent) target.attachEvent("on" + type, func); else target["on" + type] = func; } function removeEventHandler(target, type, func) { if (target.removeEventListener) target.removeEventListener(type, func, false); else if (target.detachEvent) target.detachEvent("on" + type, func); else delete target["on" + type]; } var Button1 = document.getElementById("Button1"); var test1 = function() { alert(1); }; function test2() {alert("2")} addEventHandler(Button1,"click",test1); addEventHandler(Button1,"click",test2 ); addEventHandler(Button1,"click", function() { alert("3"); } ); addEventHandler(Button1,"click", function() { alert("4"); } ); removeEventHandler(Button1,"click",test1); removeEventHandler(Button1,"click",test2); removeEventHandler(Button1,"click",function() { alert("3"); }); </script> </body> </html>