如果嵌套元素触发了一个事件,不要让容器处理它

If a nested element fires an event, dont let the container handle it

本文关键字:事件 处理 一个 元素 嵌套 如果      更新时间:2023-09-26

我有一个包含另一个div的div。如果用户单击内部div,我只希望执行附加到该元素的事件处理程序。现在首先执行内部元素的事件处理程序,然后执行外部元素的事件处理器。有办法改变这种情况吗?

    <html>
  <head>
    <meta charset="utf-8">
    <title>Demo</title>
  </head>
  <body>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script>
     $(document).ready(function(){
       $("#containerElement").click(function(event){
         alert("This comes from container");
       });
      $("#innerElement").click(function(event){
         alert("This comes from inner element");
       });
     });
   </script>

   <div id="containerElement" >
   This is the container
     <div id="innerElement" >
   This is the inner element

   </div>
   </div>
  </body>
</html>

您可以停止传播:

$("#innerElement").click(function(event){
    alert("This comes from inner element");
    event.stopPropagation();
});

添加event.stopPropagation();

$("#innerElement").click(function(event){
    alert("This comes from inner element");
    event.stopPropagation();
});

从处理程序返回false将防止冒泡(除其他外):

$("#innerElement").click(function(event){
     alert("This comes from container");
     return false;
});

event.stopPropagation()添加到您的innerElement事件处理程序中。有关更多信息,请参阅jQuery文档。

$("#innerElement").click(function(event){
    alert("This comes from inner element");
    event.stopPropagation();
});

如上所述:

http://jsbin.com/avikol/2/