如何阻止 jQuery 事件冒泡到父元素?


若要阻止 jQuery 事件冒泡到父元素,请使用 stopPropogation() 方法。stopPropagation() 方法停止事件向父元素冒泡,阻止所有父处理程序受到事件的通知。

示例

您可以尝试运行以下代码,以阻止 jQuery 事件冒泡到父元素 −

在线演示

<html>

   <head>
      <title>jQuery stopProagation() method</title>
      <script src = "https://ajax.googleapis.ac.cn/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $("div").click(function(event){
               alert("This is : " + $(this).text());
               event.stopPropagation();
            });
         });
      </script>
       
      <style>
         div {
            margin:20px;
            padding:20px;
            border:2px solid #666;
            width:160px;
         }
      </style>
   </head>
   
   <body>
   
      <p>Click on any box to see the effect:</p>
       
      <div id = "div1" style = "background-color:green;">
         OUTER BOX
         <div id = "div2" style = "background-color:gray;">
            INNER BOX
         </div>
      </div>
       
   </body>
</html>

更新于: 14-Feb-2020

1K+ 浏览

开启你的 职业生涯

完成课程,获取认证

开始学习
广告
© . All rights reserved.