绑定事件

 1 // 绑定事件   初始化分支  只需要检测浏览器1次即可  无需每次调用函数都要检测
 2     var btn = document.getElementById("btn");
 3     var btn1 = document.getElementById("btn1");
 4     
 5 
 6     var addEvent = document.body.addEventListener ? function(el, type, fn){
 7             el.addEventListener(type, fn, false);
 8         } : function(el, type, fn){
 9             el.attachEvent("on" + type, function(){
10                    fn.apply(el, arguments);
11             });
12         };
13 
14     if(typeof document.body.addEventListener === "function"){
15         console.log("ss");  // 1 次
16         addEvent = function(el, type, fn){    
17             //console.log(0);    // 2 次
18             el.addEventListener(type, fn, false);
19         };
20     }else{
21         addEvent = function(el, type, fn){
22             el.attachEvent("on" + type, function(){
23                    fn.apply(el, arguments);
24             })
25         };
26     }
27 
28     addEvent(btn, "click", function(){console.log(this)});
29     addEvent(btn1, "click", function(){console.log(this)});

 

posted @ 2013-10-14 10:45  楚玉  阅读(219)  评论(0编辑  收藏  举报