在 jQuery 中,event.preventDefault() 和 return false 有什麼區別?


在 jQuery 事件處理程式中返回 false 就像同時呼叫 preventDefault() 和 stopPropagation() 一樣。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.google.com">GOOGLE Inc.</a>
   </body>
   
</html>

示例

你可以嘗試執行以下程式碼,從 jQuery 事件處理程式中返回 false −

即時演示

<html>

   <head>
      <title>jQuery return false</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){
               alert( "Default behavior is disabled!" );
               return false;
            });
         });
      </script>
   </head>
   
   <body>
      <span>Click the following link and it won't work:</span>
      <a href = "https://www.google.com">GOOGLE Inc.</a>
   </body>
   
</html>

更新於:14-2 月-2020

569 瀏覽

開始你的 職業

完成課程獲得認證

開始
廣告