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


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

示例

您可以嘗試執行以下程式碼,以阻止 jQuery 事件冒泡到父元素 −

線上演示

<html>

   <head>
      <title>jQuery stopProagation() method</title>
      <script src = "https://ajax.googleapis.com/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.