Js事件监听封装(支持匿名函数) -- JavaScript -- IT技术博客大学习 -- 共学习 共进...
source link: https://blogread.cn/it/article/6478?f=hot1
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Js事件监听封装(支持匿名函数)
关于js中的事件监听大家用的比较多了,无非是判断浏览器是否支持addEventListener和attachEvent,网上搜索关于事件监听的方法也挺多,但是总有些不是很完善。下面的方法中对于添加事件监听的方法是一样的,只不过在取消事件绑定上面做了点手术,现在可以支持匿名函数的使用,所以在绑定事件的时候不再需要给函数单独命名了。
先看demo:http://liutian1937.github.io/demo/EventListen.html
主要代码:
/*绑定事件与取消绑定*/ var handleHash = {}; var bind = (function() { if (window.addEventListener) { return function(el, type, fn, capture) { el.addEventListener(type, function(){ fn(); handleHash[type] = handleHash[type] || []; handleHash[type].push(arguments.callee); }, capture); }; } else if (window.attachEvent) { return function(el, type, fn, capture) { el.attachEvent("on" + type, function(){ fn(); handleHash[type] = handleHash[type] || []; handleHash[type].push(arguments.callee); }); }; } })(); var unbind = (function(){ if (window.addEventListener) { return function(el, type ) { if(handleHash[type]){ var i = 0, len = handleHash[type].length; for (i; i<len ; i += 1){ el.removeEventListener(type, handleHash[type][i]); } }; }; } else if (window.attachEvent) { return function(el, type) { if(handleHash[type]){ var i = 0, len = handleHash[type].length; for (i; i<len ; i += 1){ el.detachEvent("on" + type, handleHash[type][i]); } }; }; } })();
原理解析:
handleHash做哈希表缓存事件的function,handleHash['事件名称']是一个数组,来添加多个事件监听的方法,unbind哪个事件的时候遍历handleHash['事件名称']的数组,然后移除。
使用:
bind(obj,'click',function(){ alert ('click'); }); unbind(obj,'click');
建议继续学习:
扫一扫订阅我的微信号:IT技术博客大学习
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK