JavaScript中Web应用程序事件处理
通过以下的代码来绑定事件处理代码。不仅能够为同一事件源的同一事件反复绑定事件处理代码。还能够在仅仅做一次浏览器兼容性检測的情况下完毕全部的事件处理绑定。代码例如以下所看到的: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>