兼容主流浏览器的事件处理程序

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
 5     <title>test56</title>    
 6 </head>
 7 <body>
 8     <input type="button" id="myBtn" value="点 击" name="btnName" />
 9     <script type="text/javascript" src="test56.js"></script>
10 </body>
11 </html>
 1 //EventUtil 对象
 2 var EventUtil = {
 3     addHandler: function(element, type, handler) {
 4         if (element.addEventListener) {
 5             element.addEventListener(type, handler, false);
 6         } else if (element.attachEvent) {
 7             element.attachEvent("on" + type, handler);
 8         } else {
 9             element["on" + type] = handler;
10         }
11     },
12     removeHandler: function(element, type, handler) {
13         if (element.removeEventListener) {
14             element.removeEventListener(type, handler, false);
15         } else if (element.detachEvent) {
16             element.detachEvent("on" + type, handler);
17         } else {
18             element["on" + type] = null;
19         }
20     }
21 };
22 
23 //调用 EventUtil
24 var btn = document.getElementById("myBtn");
25 var handler = function() {
26         console.log("Clicked");
27     };
28 EventUtil.addHandler(btn, "click", handler);
29 //这里省略了其他代码
30 //EventUtil.removeHandler(btn, "click", handler);
posted @ 2012-05-25 14:29  小猩猩君  阅读(184)  评论(0编辑  收藏  举报