綁定事件

 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)});
相關文章
相關標籤/搜索