Javascript 子元素点击事件触发父点击事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13966734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Child element click event trigger the parent click event
提问by Joe.wang
Say you have some code like this:
假设你有一些这样的代码:
<html>
<head>
</head>
<body>
<div id="parentDiv" onclick="alert('parentDiv');">
<div id="childDiv" onclick="alert('childDiv');">
</div>
</div>
</body>
</html>?
I don't want to trigger the parentDivclick event when I click on the childDiv, How can I do this?
我不想在parentDiv单击 时触发单击事件,我该childDiv怎么做?
Updated
更新
Also, what is the execution sequence of these two event?
另外,这两个事件的执行顺序是什么?
回答by Adil
You need to use event.stopPropagation()
$('#childDiv').click(function(event){
event.stopPropagation();
alert(event.target.id);
});?
Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
说明:防止事件在 DOM 树中冒泡,防止任何父处理程序收到该事件的通知。
回答by Akhil Sekharan
回答by Kamuran S?necek
I faced the same problem and solve it by this method. html :
我遇到了同样的问题并通过这种方法解决了它。html :
<div id="parentDiv">
<div id="childDiv">
AAA
</div>
BBBB
</div>
JS:
JS:
$(document).ready(function(){
$("#parentDiv").click(function(e){
if(e.target.id=="childDiv"){
childEvent();
} else {
parentEvent();
}
});
});
function childEvent(){
alert("child event");
}
function parentEvent(){
alert("paren event");
}
回答by pala?н
The stopPropagation()method stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.
该stopPropagation()方法会阻止事件冒泡到父元素,从而防止任何父处理程序收到该事件的通知。
You can use the method event.isPropagationStopped()to know whether this method was ever called (on that event object).
您可以使用该方法event.isPropagationStopped()来了解是否曾经调用过此方法(在该事件对象上)。
Syntax:
句法:
Here is the simple syntax to use this method:
这是使用此方法的简单语法:
event.stopPropagation()
Example:
例子:
$("div").click(function(event) {
alert("This is : " + $(this).prop('id'));
// Comment the following to see the difference
event.stopPropagation();
});?

