问题描述:
html
<div id="parent">parent
<div id="child1">child1
<div id="child2">child2</div>
</div>
</div>
js
$("#parent").on("click", "#child1", function(){
console.log("child1");
});
$("#parent").on("click", "#child2", function(){
console.log("child2");
})
这样的话,点击child2,会先打印child2,然后再打印child1
我认为过程是点击child2,然后冒泡到parent的时候触发click事件,因为parent被委托了两个click事件,所以打印了child1、child2
问题一:为什么会先打印child2,再打印child1?
当在child2的委托中调用stopPropagation
$("#parent").on("click", "#child1", function(){
console.log("child1");
});
$("#parent").on("click", "#child2", function(event){
event.stopPropagation();
console.log("child2");
})
此时点击child2,只会打印child2。点击child1,打印child1。
问题二:请问这是怎么回事?child2的委托中调用的stopPropagation,不应该是阻止parent继续往上冒泡么?