attachEvent方法绑定事件

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8">
 5         <title>attachevent、addEventListener绑定事件</title>
 6     </head>
 7     <body>
 8         <script>
 9             window.onload = function(){
10                 var oBtn = document.getElementById('btn1');
11                 
12                 
13                 //一下事件会产生冲突,最终只弹出b
14 //                oBtn.onclick = function(){
15 //                    alert('a');
16 //                }
17 //                oBtn.onclick = function(){
18 //                    alert('b');
19 //                }
20 
21 
22                 //用attachEvent方法绑定事件
23 //                oBtn.attachEvent('onclick',function(){
24 //                    alert('a');
25 //                });
26 //                oBtn.attachEvent('onclick',function(){
27 //                    alert('b');
28 //                });
29 //                
30 //                //用addEventListener方法绑定事件
31 //                oBtn.addEventListener('click',function(){
32 //                    alert('a');
33 //                },false);
34 //                oBtn.addEventListener('click',function(){
35 //                    alert('b');
36 //                },false);
37                 
38                 //兼容性写法
39 //                if(oBtn.attachEvent){
40 //                    oBtn.attachEvent('onclick',function(){
41 //                        alert('a');
42 //                    });
43 //                    oBtn.attachEvent('onclick',function(){
44 //                        alert('b');
45 //                    });
46 //                }else{
47 //                    oBtn.addEventListener('click',function(){
48 //                        alert('a');
49 //                    },false);
50 //                    oBtn.addEventListener('click',function(){
51 //                        alert('b');
52 //                    },false);
53 //                }
54 
55 
56                 //封装成方法
57                 function myAddEvent(obj,ev,fn){
58                     if(obj.attachEvent){
59                         obj.attachEvent('on' + ev,fn);
60                     }else{
61                         obj.addEventListener(ev,fn,false);
62                     }
63                 }
64                 
65                 myAddEvent(oBtn,'click',function(){
66                     alert('a');
67                 });
68                 myAddEvent(oBtn,'click',function(){
69                     alert('b');
70                 });
71             }
72         </script>
73         
74         <input type="button" value="按钮" id="btn1" />
75     </body>
76 </html>
原文地址:https://www.cnblogs.com/panda-ling/p/6699836.html