document -> f -> c
$-docum
doc: console.log(1),
f: log(2),
c: log(3);
理论
事件捕获指的是从document到触发事件的那个节点,即自上而下的去触发事件。
相反的,事件冒泡是自下而上的去触发事件。
绑定事件方法的第三个参数,就是控制事件触发顺序是否为事件捕获。true,事件捕获;false,事件冒泡。默认false,即事件冒泡。
Jquery的e.stopPropagation会阻止冒泡,意思就是到我为止,我的爹和祖宗的事件就不要触发了。
document.getElementById("parent").addEventListener("click",function(e){
alert("parent事件被触发,"+this.id);
})
document.getElementById("child").addEventListener("click",function(e){
alert("child事件被触发,"+this.id)
})
代码实现
这是HTML结构
<div id="father">
<div id="child" class="child"></div>
</div>
现在我们给它们绑定上事件
JS绑定事件
document.getElementById("father").addEventListener("click",function(e){
alert("father事件被触发,"+this.id);
})
document.getElementById("child").addEventListener("click",function(e){
alert("child事件被触发,"+this.id)
})
结果:
child事件被触发,child
father事件被触发,father
JQ绑定事件
$(function () {
$(document).on("click",".child",function(e){
console.log("child被点击了");
//e.stopPropagation(); //终止冒泡的方法
return false;
})
})
如何阻止冒泡:
实际上,冒泡的层数,会从children ,到 father,再到前面的document,即 document.getElementById中的document,
如果在JQ中写法是$("father").on("click",$("children"),function(){...}),就相当于最高级为father;
同时这也是阻止冒泡的方式之一,但不够严谨,因为有可能father本身的事件我也想禁止掉,就要用到Jquery的e.stopPropagation,会阻止冒泡;
举个栗子?:
$("#div1").mousedown(function(event){
console.log("1");
event.stopPropagation();
});
结论:先child,然后father。事件的触发顺序自内向外,这就是事件冒泡。同时强调一下:事件冒泡是默认事件,默认的,默认的,默认的
绑定捕捉事件
JS
document.getElementById("parent").addEventListener("click",function(e){
alert("parent事件被触发,"+e.target.id);
},true)
document.getElementById("child").addEventListener("click",function(e){
alert("child事件被触发,"+e.target.id)
},true)
JQ
结果:
father事件被触发,father
child事件被触发,child