簡體   English   中英

子元素單擊事件觸發父單擊事件

[英]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事件,我該怎么做?

更新

另外,這兩個事件的執行順序是什么?

你需要使用event.stopPropagation()

現場演示

$('#childDiv').click(function(event){
    event.stopPropagation();
    alert(event.target.id);
});​

event.stopPropagation()

描述:防止事件冒泡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();
});​

點擊事件Bubbles ,現在是冒泡的意思,開始的好點就在這里 你可以使用event.stopPropagation() ,如果你不希望該事件應該進一步傳播。

也是引用MDN的好鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM