測試 HTML 屬性 tabindex 是否存在並獲取其值


要獲取 HTML 屬性的值,請嘗試以下方法

$("#demo").attr("tabindex")

attr() 方法可用於獲取已匹配元素集合中第一個元素的某個屬性的值,或設定所有匹配元素上的屬性值。

還可以使用 hasAttribute() 方法檢視元素是否存在屬性。

示例

嘗試執行以下程式碼以瞭解如何使用 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("style")) {
                  alert('True')
               } else {
                  alert('False')
               }
            })
         });
      </script>
   </head>

   <body>
      <button class = 'button' style = 'background-color:blue;'>
         Button
      </button>
      <button class = 'button'>
         Button 2
      </button>
   </body>
</html>

更新於: 2020 年 1 月 29 日

355 次瀏覽

開啟你的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.