zoukankan      html  css  js  c++  java
  • Js事件监听封装(支持匿名函数)

    先看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');
  • 相关阅读:
    LeetCode 1
    Thinking in Java学习杂记(第7章)
    工程优化部分概念
    Thinking in Java学习杂记(5-6章)
    Thinking in Java学习杂记(1-4章)
    python中map()和dict()的用法
    JavaWeb高级编程(下篇)
    对CSDN的理性吐槽
    CSDN博客已经打不开了
    大连交大教务一键教学评价
  • 原文地址:https://www.cnblogs.com/hutuzhu/p/3463644.html
Copyright © 2011-2022 走看看