1 function addEventHandler(target, type, func) { 2 if (target.addEventListener) 3 target.addEventListener(type, func, false); 4 else if (target.attachEvent) 5 target.attachEvent("on" + type, func); 6 else target["on" + type] = func; 7 } 8 function removeEventHandler(target, type, func) { 9 if (target.removeEventListener) 10 target.removeEventListener(type, func, false); 11 else if (target.detachEvent) 12 target.detachEvent("on" + type, func); 13 else delete target["on" + type]; 14 }
案例:
1 var Button1 = document.getElementById("Button1"); 2 var test1 = function() { alert(1); }; 3 function test2() {alert("2")} 4 addEventHandler(Button1,"click",test1); 5 addEventHandler(Button1,"click",test2 ); 6 addEventHandler(Button1,"click", function() { alert("3"); } ); 7 addEventHandler(Button1,"click", function() { alert("4"); } ); 8 removeEventHandler(Button1,"click",test1); 9 removeEventHandler(Button1,"click",test2); 10 removeEventHandler(Button1,"click",function() { alert("3"); });
JavaScript的监听事件函数attachEvent和addEventListener使用方法
attachEvent方法,为某一事件附加其它的处理事件。(不支持Mozilla系列,用于IE8及以下版本)
addEventListener方法 用于 Mozilla系列及IE8以上IE内核浏览器。