DIV CSS 佈局教程網

getAttribute 與 setAttribute:讀寫元素的自定義屬性
編輯:JavaScript綜合知識     

兩個方法各司一職:getAttribute 讀取屬性值,setAttribute 設置屬性值。它們操作的是元素「HTML 標籤上寫的那個屬性」,而不是 JavaScript 的對象屬性——這個區別是理解它們的關鍵。

示例

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "https://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>Untitled Document</title>
  <script language="JavaScript">
    function change() {
        var input = document.getElementById("li1");

        alert(input.getAttribute("title"));        // hello
        input.setAttribute("title", "mgc");        // 改寫屬性
        alert(input.getAttribute("title"));        // mgc
    }
  </script>
</head>
<body>
  <ul id="u">
    <li id="li1" title="hello">Magci</li>
    <li>J2EE</li>
    <li>Haha!</li>
  </ul>
  <input type="button" value="Change" onClick="change();" />
</body>
</html>

第一次彈出 hello(HTML 裡寫的初始值),setAttribute 之後再讀,變成 mgc。可見 setAttribute 修改的是標籤屬性本身,刷新查看元素這段 HTML 會看到 title="mgc"。

和直接賦值的區別

對於大多數標準屬性,兩種寫法可以互換:

el.setAttribute("id", "box");
el.id = "box";                    // 等價,且更簡短

但有一類情況必須用 get/setAttribute——自定義屬性。HTML5 規範的 data-* 屬性不會自動映射成 DOM 對象屬性,只能用方法讀取:

<div id="box" data-role="panel" data-index="3"></div>

var box = document.getElementById("box");
box.getAttribute("data-role");    // "panel"
box.dataset.role;                 // "panel",HTML5 提供的便捷訪問
box.dataset.index;                // "3"

另一類必須用方法讀的情況

某些屬性直接訪問時,拿到的是計算後的結果而非 HTML 裡的原文字符串:

<a id="link" href="page.html">連結</a>

link.href;                        // 絕對 URL,如 https://example.com/page.html
link.getAttribute("href");        // "page.html",原文

同理還有 input.type 與 getAttribute("type") 的差異。需要拿到源碼裡寫的原值時,用 getAttribute。

幾個實用細節

屬性不存在時返回 null。不是空字符串,也不是 undefined。所以判斷要寫 if (el.getAttribute("x") !== null)。

返回值永遠是字符串。即使 HTML 裡寫的是 data-index="3",拿出來也是 "3",需要數值時記得 Number() 或 parseInt()。

布爾屬性的特殊性。像 disabled、checked 這類,el.disabled 返回真正的布爾值,而 getAttribute("disabled") 只要有這個屬性就返回空字符串 ""(在 if 中為假!)。判斷這類狀態要用對象屬性,或用 el.hasAttribute("disabled")。

删除屬性用 removeAttribute。

el.removeAttribute("style");

class 有專屬 API。操作 class 時不要拼字符串,用 classList 更安全:

el.classList.add("active");
el.classList.remove("hide");
el.classList.toggle("open");

總結一句:標準屬性優先用 el.xxx 屬性訪問,data-* 用 dataset,需要原文或處理自定義屬性時再用 get/setAttribute。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved