在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Java  HTML/ 原生js怎么實(shí)現(xiàn)jquery .on( events, selector, ha

原生js怎么實(shí)現(xiàn)jquery .on( events, selector, handler )委派事件??

jquery中如下可以實(shí)現(xiàn)事件委派,動(dòng)態(tài)添加的tr也會(huì)觸發(fā)該事件

$( "#dataTable tbody" ).on( "click", "tr", function() {
  console.log( $( this ).text() );
});

在原生js中該怎么實(shí)現(xiàn)該功能?

回答
編輯回答
愛是癌

上面這位大佬的方法很標(biāo)注,很嚴(yán)禁,但不適合小白理解:

首先要明白委托是什么意思:委托并沒有給子元素綁定事件,點(diǎn)擊子元素的時(shí)候根據(jù)事件冒泡的原理,觸發(fā)了body上綁定的事件,這個(gè)方法是能獲取到點(diǎn)擊的子元素的事件對(duì)象的,這個(gè)比較簡單;
難點(diǎn)其實(shí)是另一個(gè)問題,子元素dom結(jié)構(gòu)通常不止1層,那么如何讓事件對(duì)象是我們想要那個(gè),一般要的是子元素最外層的元素,下面一個(gè)栗子可以告訴你怎么獲取你想要的父節(jié)點(diǎn)的事件對(duì)象:

var a=document.getElementById('content_left');//以百度搜索結(jié)果列表為例
a.onclick = function(ev){//這個(gè)ev是你點(diǎn)擊的那個(gè)子元素的子元素
            var ev = ev || window.event;
            var target = ev.target || ev.srcElement;
        while(target!=a){//在非父節(jié)點(diǎn)中尋找最外層dom
            console.log(target.className)
                        if(target.className == 'c-abstract'){//c-abstract是我想要的每一項(xiàng)列表的最外層
                            target.style.background = "#eee";
                break;
                    }
        target=target.parentNode;//通過while,逐級(jí)尋找父節(jié)點(diǎn)
     }
};
2017年1月9日 20:43
編輯回答
只愛你
function eventDelegate (e,targetSelector,fn) {
    // 兼容性處
    let event = e || window.event;

    // 獲取到目標(biāo)階段指向的元素
    let target = event.target || event.srcElement;

    // 獲取到代理事件的函數(shù)
    let currentTarget = event.currentTarget;

    // 處理 matches 的兼容性
    if (!Element.prototype.matches) {
      Element.prototype.matches =
        Element.prototype.matchesSelector ||
        Element.prototype.mozMatchesSelector ||
        Element.prototype.msMatchesSelector ||
        Element.prototype.oMatchesSelector ||
        Element.prototype.webkitMatchesSelector ||
        function(s) {
          let matches = (this.document || this.ownerDocument).querySelectorAll(s),
            i = matches.length;
          while (--i >= 0 && matches.item(i) !== this) {}
          return i > -1;
        };
    }

    // 遍歷外層并且匹配
    while (target !== currentTarget) {
      // 判斷是否匹配到我們所需要的元素上
      if (target.matches(targetSelector)) {
        let sTarget = target;
        // 執(zhí)行綁定的函數(shù),注意 this
        fn.call(sTarget, Array.prototype.slice.call(arguments))
      }

      target = target.parentNode;
    }
2018年4月17日 03:13