如何使用 jQuery 中的 hasClass() 方法?


hasClass() 方法用於檢查元素是否具有某個類。你可以嘗試執行以下程式碼以瞭解如何在 jQuery 中使用 hasClass() 方法 −

範例

動態演示

<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         $(document).ready(function(){
             $("button").click(function(){
                 alert($("h1").hasClass("myclass"));
             });
         });
      </script>
      <style>
         .myclass {
           color: blue;
         }
      </style>
   </head>
   <body>
      <h1 class="myclass">Heading</h1>
      <p>This is demo text.</p>
      <button>Check: The h1 element has 'myclass' class?</button>
   </body>
</html>

更新日期: 14-Feb-2020

116 次瀏覽

開啟你的職業

完成課程以取得認證

開始
廣告
© . All rights reserved.