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等,不适合事件委托

  • 相关阅读:
    xml解析模块
    python面向对象基础
    python hashlib模块
    os和sys模块
    python反射
    正则表达式re模块
    踩的python列表及for循环一个坑儿
    python序列化模块json和pickle
    python时间模块-time和datetime
    64匹马、8赛道,至少多少轮比赛找出速度最快的4匹马?
  • 原文地址:https://www.cnblogs.com/mengff/p/6508741.html
Copyright © 2011-2022 走看看