简体   繁体   English

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

[英]Child element click event trigger the parent click event

Say you have some code like this: 假设你有这样的代码:

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

I don't want to trigger the parentDiv click event when I click on the childDiv , How can I do this? 当我点击childDiv时,我不想触发parentDiv click事件,我该怎么做?

Updated 更新

Also, what is the execution sequence of these two event? 另外,这两个事件的执行顺序是什么?

You need to use event.stopPropagation() 你需要使用event.stopPropagation()

Live Demo 现场演示

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

event.stopPropagation() event.stopPropagation()

Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. 描述:防止事件冒泡DOM树,防止任何父处理程序被通知事件。

Without jQuery : DEMO 没有jQuery: DEMO

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

I faced the same problem and solve it by this method. 我遇到了同样的问题并通过这种方法解决了。 html : HTML:

<div id="parentDiv">
   <div id="childDiv">
     AAA
   </div>
    BBBB
</div>

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

The stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event. stopPropagation()方法停止将事件冒泡到父元素,从而阻止任何父处理程序被通知事件。

You can use the method event.isPropagationStopped() to know whether this method was ever called (on that event object). 您可以使用event.isPropagationStopped()方法来了解是否曾调用此方法(在该事件对象上)。

Syntax: 句法:

Here is the simple syntax to use this method: 以下是使用此方法的简单语法:

event.stopPropagation() 

Example: 例:

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

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

Click event Bubbles , now what is meant by bubbling, a good point to starts is here . 点击事件Bubbles ,现在是冒泡的意思,开始的好点就在这里 you can use event.stopPropagation() , if you don't want that event should propagate further. 你可以使用event.stopPropagation() ,如果你不希望该事件应该进一步传播。

Also a good link to refer on MDN 也是引用MDN的好链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM