js binding event method: addEventListener compatibility issues

js event binding methods, ie only supports attachEvent, while FF and Chrome only supports addEventListener; strictly speaking: addEventListener IE9 is only compatible with the above versions of IE browser, IE8 or lower version is not supported at this time to be able to lower version compatible with IE browser will need to determine the current browser and then decide which one to use for different browsers.

  The difference attachEvent and addEventLitener second argument is the name of the event to be more a "on", such as 'onclick', and he's this points to the window, when in use need to change this point. Here is a compatible wording:

 1 var Event = {};
 2 Event.addEvents = function(target,eventType,handle){
 3         if(document.addEventListener){
 4                Event.addEvents = function(target,eventType,handle){
 5                       target.addEventListener(eventTypt,handle,false);
 6         };
 7     }else {
 8         Event.addEvents = function(target,eventType,handle){
 9             target.attachEvent('on' eventType,function(){
10                 handle.call(target,arguments);
11             });
12         };
13     
14     }
15     Event.addEvents(target,eventType,handle);
16 
17     }                    

Call the method:

1 Event.addEvents(document,"click",function(){
2         alert(ok)
3 });

 

Published an original article · won praise 2 · views 10000 +

Guess you like

Origin blog.csdn.net/u011927449/article/details/104030307