导航

自定义事件并且主动触发

Posted on 2018-05-31 18:17  小飞博客  阅读(430)  评论(0编辑  收藏  举报
 1 <!DOCTYPE HTML>
 2 <html>
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 5 <title>自定义事件并且主动触发</title>
 6 </head>
 7 <body>
 8 <div id="div1">div</div>
 9 <span id="span1">span</span>
10 </body>
11 <script>
12 
13     var oDiv = document.getElementById('div1');
14     var oSpan = document.getElementById('span1');
15     bindEvent(oDiv , 'click',function(){
16         alert(3);
17     });
18     bindEvent(oSpan , 'gogo',function(){
19         alert(4);
20     });
21     fireEvent(oSpan , 'gogo');  //3 , 4
22     function bindEvent(obj,events,fn){
23         obj.listeners = obj.listeners || {};
24         obj.listeners[events] = obj.listeners[events] || [];
25         obj.listeners[events].push( fn );
26         if(obj.addEventListener){
27             obj.addEventListener(events,fn,false);
28         }
29         else{
30             obj.attachEvent('on'+events,fn);
31         }
32     }
33     //主动触发自定义事件
34     function fireEvent(obj,events){   
35         for(var i=0;i<obj.listeners[events].length;i++){
36             obj.listeners[events][i]();
37         } 
38     }
39 </script>
40 </html>