您的位置:首页 > Web前端 > JQuery

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

2016-10-28 19:34 344 查看
先简单说明下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需要响应的控件渲染完毕才可以执行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: