子元素单击事件触发父单击事件 [英] Child element click event trigger the parent click event

查看:261
本文介绍了子元素单击事件触发父单击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有这样的代码:

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

我不想触发<$ c当我点击 childDiv 时,$ c> parentDiv 点击事件,我该怎么做?

I don't want to trigger the parentDiv click event when I click on the childDiv, How can I do this?

已更新

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

Also, what is the execution sequence of these two event?

推荐答案

您需要使用 event.stopPropagation()

现场演示

Live Demo

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

event.stopPropagation()


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

Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

这篇关于子元素单击事件触发父单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆