jQuery event.stopPropagation() 方法



jQuery 的event.stopPropagation() 方法阻止事件冒泡到父元素,防止任何父元素的處理程式收到事件通知。這意味著當觸發事件時,它不會傳播到父元素,從而防止任何父事件處理程式執行。

您可以使用方法 event.isPropagationStopped() 來了解此方法是否曾經被呼叫(在該事件物件上)。

語法

以下是 jQuery event.stopPropagation() 方法的語法:

event.stopPropagation() 

引數

此方法不接受任何引數。

返回值

此方法不返回值。

示例 1

以下程式演示了 jQuery event.stopPropagation() 方法的使用:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <style>
        div{
            width: 200px;
            padding: 20px;
        }
    </style>
</head>
<body>
   <p>Click on any box to see the effect:</p>
   <div id="div1" style="background-color:blue;">
       OUTER BOX
       <div id="div2" style="background-color:red;">
             INNER BOX
      </div> 
  </div>
  <script>
  $(document).ready(function() {
    $("div").click(function(event){
        alert("This is : " + $(this).text()); // Comment the following to see the difference
        event.stopPropagation();
    });
});
  </script>
</body>
</html>

輸出

以上程式顯示了一個巢狀的 div 元素,其中包含一些文字。當我們點選任何一個 div 時,都會出現一個相應的彈出警報,指示點選了哪個 div:


示例 2

使用event.isPropagationStopped() 方法以及event.stopPropagation() 方法來檢查此方法是否曾經被呼叫:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <style>
        div{
            width: 200px;
            padding: 20px;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 20px;
        }
    </style>
</head>
<body>
   <p>Click on any box to see the effect:</p>
   <div id="div1" style="background-color:rgb(69, 238, 100);">
       Outer Div 
       <div id="div2" style="background-color:rgb(13, 138, 13);">
             INNER Div
      </div> 
  </div>    
  <p>Click on the below button to check whether propagation stopped or not.</p>
  <button>Check</button><span></span>
  <script>
  $(document).ready(function() {
    $("div").click(function(event){
        $('span').text("This is : " + $(this).text());
        event.stopPropagation();
        $('button').click(function(){
            if(event.isPropagationStopped()){
                $('span').text("Is propagation stopped? " + event.isPropagationStopped());
            }
            else{
                $('span').text("Is propagation stopped? " + event.isPropagationStopped());
            }
        });
    });
});
  </script>
</body>
</html>

輸出

執行以上程式後,會顯示兩個巢狀的 div 和一個按鈕元素。當點選任何一個 div 時,都會顯示訊息,指示點選了哪個 div。如果點選了按鈕,則會列印“true”:


jquery_ref_events.htm
廣告

© . All rights reserved.