子元素点击事件触发父元素的点击事件

91

假设你有以下代码:

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

当我点击childDiv时,我不想触发parentDiv的点击事件,我该怎么做?

更新

还有,这两个事件的执行顺序是什么?


3
这被称为事件冒泡,一个很好的起点是:https://dev59.com/4W445IYBdhLWcg3w9Oss - Pranav
2
这个问题的标题应该是“阻止子事件点击触发父事件点击”,但它读起来相反。 - Iwnnay
5个回答

117

7
如果你有针对父元素和子元素点击事件的两个独立的处理程序,并且你只想通过子元素的点击事件触发子元素的处理程序,那么你必须在子元素上调用event.stopPropagation()方法,而不是在父元素上调用。 - tsveti_iko

25

没有使用jQuery:演示

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

1
谢谢@Akhil,这对我有用。 - amol rajput

9

我遇到了同样的问题,并通过这种方法解决了它。

<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");
}

7
stopPropagation()方法可以停止事件冒泡到父元素,防止任何父处理程序被通知该事件。您可以使用event.isPropagationStopped()方法来了解是否曾在该事件对象上调用过此方法。 语法: 以下是使用此方法的简单语法:
event.stopPropagation() 

例子:

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

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

6
点击事件冒泡,什么是冒泡?一个好的起点可以从这里开始。如果您不希望事件继续传播,可以使用event.stopPropagation()
此外,MDN也是一个很好的参考链接。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接