【问题标题】:Child element click event trigger the parent click event子元素点击事件触发父点击事件
【发布时间】:2012-12-07 15:39:11
【问题描述】:

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

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

我不想在点击childDiv时触发parentDiv点击事件,怎么办?

更新

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

【问题讨论】:

  • 这被称为事件冒泡,一个好的开始:- stackoverflow.com/questions/4616694/…
  • 这个问题的题目应该是“Stop child event click from trigger parent click event” 读起来正好相反。

标签: javascript jquery dhtml


【解决方案1】:

你需要使用event.stopPropagation()

Live Demo

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

event.stopPropagation()

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

【讨论】:

  • 如果您有 2 个单独的父子点击事件处理程序,并且您想通过子点击事件仅触发子处理程序,则必须调用 event.stopPropagation() childDiv,不在 parentDiv 上
【解决方案2】:

没有 jQuery:DEMO

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

【讨论】:

  • 谢谢@Akhil 它对我有用。
【解决方案3】:

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

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

【讨论】:

    【解决方案4】:

    stopPropagation() 方法停止将事件冒泡到父元素,防止任何父处理程序收到事件通知。

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

    语法:

    这是使用此方法的简单语法:

    event.stopPropagation() 
    

    示例:

    $("div").click(function(event) {
        alert("This is : " + $(this).prop('id'));
    
        // Comment the following to see the difference
        event.stopPropagation();
    });​
    

    【讨论】:

      【解决方案5】:

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

      MDN上也是一个很好的参考链接

      【讨论】:

        猜你喜欢
        • 2017-12-05
        • 2023-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-05
        相关资源
        最近更新 更多