关于原生事件绑定和jquery的On


先简单说明下addEventListener这个函数,代码如下:
1.window.onload = function(){  
    var a = document.getElementById("a");  
    a.addEventListener("click",function(){  
        console.log("a1");  
    })  
    a.addEventListener("click",function(){  
        console.log("a2");  
    })  
}  
输出结果:
a1
a2

2.
<body>
  <div id="parent">
    <div id="child"></div>
  </div>
</body>
parent.addEventListener("click",function(){  
    console.log("parent");  
})  
  
child.addEventListener("click",function(){  
    console.log("child");  
})  
输出结果:
child
parent

3.parent.addEventListener("click",function(){  
    console.log("parent");  
},true)  
  
child.addEventListener("click",function(){  
    console.log("child");  
}) 
输出结果:
parent
child


2.真正的问题来了,addEventListener vs on

摘自一段英文解答,有兴趣的同学可以看下:

When you use .on() at the document level, you're waiting for the event to bubble all the way up to that point. The event handler for any intermediate container will already have been called.

Event "bubbling" is the process by which the browser looks for event handlers registered with parents of the element that was the actual original recipient of the event. It works upwards in the DOM tree. The document level is the last level checked. Thus, your handler registered with .on() won't run until that level is reached. In the meantime, the other event handler at the "outer" level is reached first and it is executed by the browser.

Thus, that return false; in the handler registered with .on() is pretty much useless, as would be a call to event.stopPropagation(). Beyond that, mixing native event handler registration with the work that a library like jQuery will do is probably a really bad idea unless you seriously know what you're doing.

我的理解就是,前者可以在页面还没加载完,也就是DOM树还未生成的时候就可以执行,而on需要响应的控件渲染完毕才可以执行。







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值