JavaScript 綁定多事件

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title></title>
 6         <style>
 7             #div1{width: 200px;height:200px;background-color:red;position: absolute;}
 8         </style>
 9         <script>
10             function myAddEvent(obj,ev,fn){
11                 if(obj.attachEvent){
12                     obj.attachEvent('on'+ev,fn);
13                 }
14                 else{
15                     obj.addEventListener(ev,fn,false);
16                 }
17             }
18             window.onload=function(){
19                 var oBtn=document.getElementById('btn1');
20 
21                 //只彈出 b
22                 // oBtn.onclick=function(){
23                 //     alert('a');
24                 // }
25                 // oBtn.onclick=function(){
26                 //     alert('b');
27                 // }
28 
29 
30                 // //IE
31                 // //attachEvent(事件名,函數)
32                 // //detachEvent(事件名稱,函數),解除綁定
33                 // oBtn.attachEvent('onclick',function(){
34                 //     alert('a');
35                 // })
36                 // oBtn.attachEvent('onclick',function(){
37                 //     alert('b');
38                 // })
39 
40                 // //FF
41                 // //removeEventListener(事件名,函數,捕獲)
42                 // //addEventListener(事件名,函數,false)
43                 // oBtn.addEventListener('click',function(){
44                 //     alert('a');
45                 // },false);
46                 // oBtn.addEventListener('click',function(){
47                 //     alert('b');
48                 // },false);
49 
50                 // if(oBtn.attachEvent){
51                 //     oBtn.attachEvent('onclick',function(){
52                 //         alert('a');
53                 //     })
54                 //     oBtn.attachEvent('onclick',function(){
55                 //         alert('b');
56                 //     })
57                 // }
58                 // else{
59                 //     oBtn.addEventListener('click',function(){
60                 //         alert('a');
61                 //     },false);
62                 //     oBtn.addEventListener('click',function(){
63                 //         alert('b');
64                 //     },false);
65                 // }
66 
67                 myAddEvent(oBtn,'click',function(){
68                     alert('a');
69                 })
70                 myAddEvent(oBtn,'click',function(){
71                     alert('b');
72                 })
73             }
74         </script>
75     </head>
76     <body>
77         <input id="btn1" type="button" value="按鈕" />
78     </body>
79 </html>
View Code

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章