2012-12-20 223 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"); 
}