子元素单击事件触发父单击事件

Joe*_*ang 58 javascript jquery dhtml

假设你有这样的代码:

<html>
<head>
</head>
<body>
   <div id="parentDiv" onclick="alert('parentDiv');">
       <div id="childDiv" onclick="alert('childDiv');">
       </div>   
    </div>
</body>
</html>?
Run Code Online (Sandbox Code Playgroud)

parentDiv当我点击" childDiv我怎么能这样做?" 时,我不想触发点击事件?

更新

另外,这两个事件的执行顺序是什么?

Adi*_*dil 76

你需要使用event.stopPropagation()

现场演示

$('#childDiv').click(function(event){
    event.stopPropagation();
    alert(event.target.id);
});?
Run Code Online (Sandbox Code Playgroud)

event.stopPropagation()

描述:防止事件冒泡DOM树,防止任何父处理程序被通知事件.

  • 如果你有两个单独的处理程序用于父项和子项单击事件,并且你想通过子项上的click事件仅触发子处理程序,则必须在childDiv上调用event.stopPropagation(),而不是在parentDiv上调用 (6认同)

Akh*_*ran 20

没有jQuery:DEMO

 <div id="parentDiv" onclick="alert('parentDiv');">
   <div id="childDiv" onclick="alert('childDiv');event.cancelBubble=true;">
     AAA
   </div>   
</div>
Run Code Online (Sandbox Code Playgroud)


Kam*_*cek 7

我遇到了同样的问题并通过这种方法解决了.HTML:

<div id="parentDiv">
   <div id="childDiv">
     AAA
   </div>
    BBBB
</div>
Run Code Online (Sandbox Code Playgroud)

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");
}
Run Code Online (Sandbox Code Playgroud)


pal*_*aѕн 6

stopPropagation()方法停止将事件冒泡到父元素,从而阻止任何父处理程序被通知该事件.

您可以使用该方法event.isPropagationStopped()来了解是否曾调用此方法(在该事件对象上).

句法:

以下是使用此方法的简单语法:

event.stopPropagation() 
Run Code Online (Sandbox Code Playgroud)

例:

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

    // Comment the following to see the difference
    event.stopPropagation();
});?
Run Code Online (Sandbox Code Playgroud)


Pra*_*nav 5

单击事件冒泡,现在冒泡是什么意思,一个好的开始点就在这里。您可以使用event.stopPropagation(), 如果您不希望该事件进一步传播。

也是一个很好的链接,可以参考MDN