zoukankan      html  css  js  c++  java
  • 事件委托优缺点和实现

    function fDelegate(parentSelector,targetSelector,event,callback){
        var parent = document.querySelector(parentSelector);
        parent.addEventListener(event,fEventHandler,false);
    
        function fEventHandler(e){
            var target = e.target,
                //currentTarget = e.currentTarget;//parent代替
            while(target != parent){
                if(target.matches(targetSelector)){
                    callback.apply(target,Array.prototype.slice.call(arguments));
                    break;
                }
                target = target.parentNode;
            }
        }
    }
    
    if (!Element.prototype.matches) {
      Element.prototype.matches =
        Element.prototype.matchesSelector ||
        Element.prototype.mozMatchesSelector ||
        Element.prototype.msMatchesSelector ||
        Element.prototype.oMatchesSelector ||
        Element.prototype.webkitMatchesSelector ||
        function(s) {
          var matches = (this.document || this.ownerDocument).querySelectorAll(s),
          i = matches.length;
          while (--i >= 0 && matches.item(i) !== this) {}
          return i > -1;
        };
    }

    调用:

    fDelegate('#list', 'li', 'click', function () { console.log(this); });

    事件委托优点:

    1.减少内存消耗,不必为大量元素绑定事件
    2.为动态添加的元素绑定事件

    事件委托的缺点:

    1.部分事件如 focus、blur 等无冒泡机制,所以无法委托。
    2.事件委托有对子元素的查找过程,委托层级过深,可能会有性能问题
    3.频繁触发的事件如 mousemove、mouseout、mouseover等,不适合事件委托

  • 相关阅读:
    poj 1579(动态规划初探之记忆化搜索)
    hdu 1133(卡特兰数变形)
    CodeForces 625A Guest From the Past
    CodeForces 625D Finals in arithmetic
    CDOJ 1268 Open the lightings
    HDU 4008 Parent and son
    HDU 4044 GeoDefense
    HDU 4169 UVALive 5741 Wealthy Family
    HDU 3452 Bonsai
    HDU 3586 Information Disturbing
  • 原文地址:https://www.cnblogs.com/mengff/p/6508741.html
Copyright © 2011-2022 走看看