[英]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.