为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

宝慕林4294392 2019-03-05 17:12:26
jquery中如下可以实现事件委派,动态添加的tr也会触发该事件$( "#dataTable tbody" ).on( "click", "tr", function() {  console.log( $( this ).text() );});在原生js中该怎么实现该功能?
查看完整描述

2 回答

?
子衿沉夜

TA贡献1828条经验 获得超3个赞

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;

    }


查看完整回答
反对 回复 2019-03-28
  • 2 回答
  • 0 关注
  • 635 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号