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

  • 相关阅读:
    Linux内存管理2---段机制
    XCOJ 1102 (树形DP+背包)
    ZOJ 3805 (树形DP)
    Ural 1018 (树形DP+背包+优化)
    POJ 2342 (树形DP)
    HDU 2612 (BFS搜索+多终点)
    POJ 1947 (树形DP+背包)
    HDU 1561 (树形DP+背包)
    HDU 1045 (DFS搜索)
    HDU 5067 (状态压缩DP+TSP)
  • 原文地址:https://www.cnblogs.com/mengff/p/6508741.html
Copyright © 2011-2022 走看看