[英]Child element click event trigger the parent click event
假设你有这样的代码:
<html>
<head>
</head>
<body>
<div id="parentDiv" onclick="alert('parentDiv');">
<div id="childDiv" onclick="alert('childDiv');">
</div>
</div>
</body>
</html>
当我点击childDiv
时,我不想触发parentDiv
click事件,我该怎么做?
更新
另外,这两个事件的执行顺序是什么?
$('#childDiv').click(function(event){
event.stopPropagation();
alert(event.target.id);
});
描述:防止事件冒泡DOM树,防止任何父处理程序被通知事件。
没有jQuery: DEMO
<div id="parentDiv" onclick="alert('parentDiv');">
<div id="childDiv" onclick="alert('childDiv');event.cancelBubble=true;">
AAA
</div>
</div>
我遇到了同样的问题并通过这种方法解决了。 HTML:
<div id="parentDiv">
<div id="childDiv">
AAA
</div>
BBBB
</div>
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");
}
stopPropagation()
方法停止将事件冒泡到父元素,从而阻止任何父处理程序被通知事件。
您可以使用event.isPropagationStopped()
方法来了解是否曾调用此方法(在该事件对象上)。
句法:
以下是使用此方法的简单语法:
event.stopPropagation()
例:
$("div").click(function(event) {
alert("This is : " + $(this).prop('id'));
// Comment the following to see the difference
event.stopPropagation();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.