jQuery 中 event.preventDefault() 和 event.stopPropagation() 有什麼區別?


stopPropogation() 方法

要阻止事件冒泡到父元素,請使用 stopPropagation() 方法。

示例

你可以嘗試執行以下程式碼,瞭解如何使用 stopPropogation() 方法

試用版

<html>

   <head>
      <title>jQuery stopPropagation() method</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            $("div").click(function(event){
               alert("This is : " + $(this).text());
               
               event.stopPropagation();
            });
         });
      </script>
       
      <style>
         div {
             margin:10px;
             padding:12px;
             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:blue;">
         OUTER BOX
         <div id = "div2" style = "background-color:red;">
            INNER BOX
         </div>
      </div>
       
   </body>
</html>

preventDefault() 方法

preventDefault() 方法阻止瀏覽器執行預設操作。

示例

你可以嘗試執行以下程式碼,在 jQuery 中執行 event.preventDefault() 方法

試用版

<html>

   <head>
      <title>jQuery preventDefault() method</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $("a").click(function(event){
               event.preventDefault();
               alert( "Default behavior is disabled!" );
            });
         });
      </script>
   </head>
   
   <body>
      <span>Click the following link and it won't work:</span>
      <a href = "https://www.qries.com">Qries</a>
   </body>
   
</html>

更新於: 2019-12-11

177 次瀏覽

開啟您的 職業生涯

透過完成課程來獲得認證

開始
廣告