如何阻止 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>

更新於: 2020 年 2 月 14 日

超過 1K 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告