如何在 jQuery 中查詢某個屬性是否適用於選中的專案?


要查詢某個屬性是否存在於 jQuery 中的選定專案,請使用 hasAttribute() 方法。

示例

你可以嘗試執行以下程式碼,瞭解如何查詢某個屬性是否存在

即時演示

<!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').on('click', function() {
                if (this.hasAttribute("myattr")) {
                   alert('True - myattr attribute exists')
                } else {
                   alert('False - myattr attribute does not exist')
                }
            })
         });
      </script>
   </head>
   <body>
      <button class='button' style='color: green' myattr='demo'>
      Button One
      </button>
      <button class='button'>
      Button Two
      </button>
   </body>
</html>

更新於:18-12-2019

137 次瀏覽

開啟你的 職業

透過完成課程取得認證

開始
廣告
© . All rights reserved.