2012-12-20 326 views
43

說你有一些像這樣的代碼:兒童元素點擊事件觸發父點擊事件

<html> 
<head> 
</head> 
<body> 
    <div id="parentDiv" onclick="alert('parentDiv');"> 
     <div id="childDiv" onclick="alert('childDiv');"> 
     </div> 
    </div> 
</body> 
</html>​ 

我不想觸發,當我點擊childDivparentDiv點擊事件,我該怎麼做?

更新

此外,什麼是這兩個事件的執行順序?

+3

這就是所謂的事件冒泡,好點開始: - HTTP://計算器。com/questions/4616694/what-is-event-bubbling-and-capturing – Pranav

回答

49

您需要使用event.stopPropagation()

Live Demo

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

event.stopPropagation()

說明:防止被通知冒泡DOM樹, 防止任何父處理程序從事件的事件。

+4

如果您有兩個單獨的處理程序用於父級和子級單擊事件,並且您希望僅通過子級上的單擊事件觸發子級處理程序,在childDiv上調用event.stopPropagation(),而不是在parentDiv上 –

12

沒有jQuery的:DEMO

<div id="parentDiv" onclick="alert('parentDiv');"> 
    <div id="childDiv" onclick="alert('childDiv');event.cancelBubble=true;"> 
    AAA 
    </div> 
</div> 
6

stopPropagation()方法停止事件的冒泡到父元素,防止任何父處理程序從被通知的事件。

您可以使用方法event.isPropagationStopped()來了解此方法是否曾被調用(在該事件對象上)。

語法:

下面是簡單的語法使用此方法:

event.stopPropagation() 

例子:

$("div").click(function(event) { 
    alert("This is : " + $(this).prop('id')); 

    // Comment the following to see the difference 
    event.stopPropagation(); 
});​ 
3

Click事件氣泡,現在是什麼意思通過冒泡,開始的好點是here。 如果您不希望該事件進一步傳播,則可以使用event.stopPropagation()

也是一個很好的鏈接將關於MDN

3

我面臨同樣的問題,通過這種方法解決它。 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"); 
}