通过下面的代码来绑定事件处理代码,不仅可以为同一事件源的同一事件重复绑定事件处理代码,还可以在只做一次浏览器兼容性检测的情况下完成所有的事件处理绑定。代码如下所示: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>