我有一个简单的场景:我有两个 div 一个在另一个里面,我希望当我单击子 div 时,仅子 div 调用,当我单击父 div 时,父 div 调用,但在下面的示例中,您可以看到我单击子项,两者都会被调用。这是我的代码:
$(document).ready(function(){
$("#t1").click(function(){alert("Parent")});
$("#t2").click(function(){alert("child")});
});
http://jsfiddle.net/hminaee/hv6dv/
有人可以帮忙吗?
最佳答案
您应该使用 event.stopPropagation()
阻止事件在 DOM 树中冒泡(任何父处理程序都不会收到该事件的通知) 。尝试:
$(document).ready(function(){
$("#t1").click(function(){alert("Parent")});
$("#t2").click(function(e){e.stopPropagation();alert("child")});
});
<强> DEMO
关于javascript - 当我单击 div 元素中的 child 时,如何才能调用 child,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22110559/