通過下面的代碼來綁定事件處理代碼,不僅可以為同一事件來源的同一事件重複綁定事件處理代碼,還可以在只做一次瀏覽器安全色性檢測的情況下完成所有的事件處理綁定。代碼如下所示:js/mylib.js
var addEvent = function(target, name, fn) { if(target.addEventListener) addEvent = function(target, name, fn) { target.addEventListener(name, fn, false); }; else if(target.attachEvent) addEvent = function(target, name, fn) { target.attachEvent('on' + name, fn); }; addEvent(target, name, fn);};
下面是測試代碼:test.html
<!DOCTYPE html><html> <head> <title>Sample Page</title> <script type="text/javascript" src="js/mylib.js"></script> <script type="text/javascript"> addEvent(window, "load", init); function init() { addEvent(document.getElementById('ok'), "click", foo); addEvent(document.getElementById('ok'), 'click', bar); } function foo() { alert('foo'); } function bar() { alert('bar'); } </script> </head> <body> <button id="ok">OK</button> </body></html>