原生js怎么实现jquery .on( events, selector, handler )

jquery中如下可以实现事件委派,动态添加的tr也会触发该事件


$( "#dataTable tbody" ).on( "click", "tr", function() {

  console.log( $( this ).text() );

});

在原生js中该怎么实现该功能?


宝慕林4294392
浏览 636回答 2
2回答

子衿沉夜

function eventDelegate (e,targetSelector,fn) {    // 兼容性处    let event = e || window.event;    // 获取到目标阶段指向的元素    let target = event.target || event.srcElement;    // 获取到代理事件的函数    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;        // 执行绑定的函数,注意 this        fn.call(sTarget, Array.prototype.slice.call(arguments))      }      target = target.parentNode;    }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript