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

2023-11-30

假设你有一些这样的代码:

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

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

Updated

另外,这两个事件的执行顺序是怎样的?


你需要使用event.stopPropagation()

现场演示

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

event.stopPropagation()

描述:防止事件在 DOM 树中冒泡, 防止任何父处理程序收到该事件的通知。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

子元素点击事件触发父元素点击事件 的相关文章