关于js注册事件的常用方法
不解释,看代码:
代码如下:
;(function(){ //进行库封装,防止对象污染 window['cm']={}; /** *给对象注册事件 */ var addListener=function(element,type,fn){ if(typeof element == 'undefined') return false; if(element.addEventListener){ element.addEventListener(type,fn,false); }else if(element.attachEvent){ //将事件缓冲到该标签上,已解决this指向window(现fn内this指向element)和移除匿名事件问题 var _EventRef='_'+type+'EventRef'; if(!element[_EventRef]){ element[_EventRef]=[]; } var _EventRefs=element[_EventRef]; var index; for(index in _EventRefs){ if(_EventRefs[index]['realFn']==fn){ return; } } var nestFn=function(){ fn.apply(element,arguments); }; element[_EventRef].push({'realFn':fn,'nestFn':nestFn}); element.attachEvent('on'+type,nestFn); }else{ element['on'+type]=fn; } }; window['cm']['addListener']=addListener; /** *移除对象上已注册事件 */ var removeListener=function(element,type,fn){ if(typeof element == 'undefined') return false; if(element.removeEventListener){ element.removeEventListener(type,fn,false); }else if(element.detachEvent){ var _EventRef='_'+type+'EventRef'; if(!element[_EventRef]){ element[_EventRef]=[]; } var _EventRefs=element[_EventRef] var index; var nestFn; for(index in _EventRefs){ if(_EventRefs[index]['realFn']==fn){ nestFn=_EventRefs[index]['nestFn']; if(index==_EventRefs.length-1){ element[_EventRef]=_EventRefs.slice(0,index); }else{ element[_EventRef]=_EventRefs.slice(0,index).concat(_EventRefs.slice(index+1,_EventRefs.length-1)); } break; } } if(nestFn){ element.detachEvent('on'+type,nestFn); } }else{ element['on'+type]=null; } }; })();
相关推荐
wikiwater 2020-10-27
阿斌Elements 2020-06-11
IdeaElements 2020-08-19
Sophiego 2020-08-16
Kakoola 2020-08-01
Kakoola 2020-07-29
ELEMENTS爱乐冬雨 2020-07-18
ELEMENTS爱乐小超 2020-07-04
ELEMENTS爱乐小超 2020-07-04
Kakoola 2020-06-28
Feastaw 2020-06-18
Wmeng0 2020-06-14
ELEMENTS爱乐冬雨 2020-06-14