萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript property vs attribute 深度解析:定義、同步、差異、兼容性、最佳實踐

定義區分

概念Property (屬性)Attribute (特性/屬性)
所屬DOM 對象 (JS 對象)HTML 標籤標記
值類型任意 JS 類型僅字符串
大小寫敏感不敏感
可見性不出現在 outerHTML出現在 outerHTML / innerHTML
訪問方式el.prop / el['prop']el.getAttribute() / el.setAttribute()

同步機制

標準屬性雙向同步:id、className/class、title、style、href、src、value (輸入框) 等。

// 修改 property → attribute 同步更新
el.id = "newId";
el.getAttribute("id"); // "newId"

// 修改 attribute → property 同步更新
el.setAttribute("title", "tip");
el.title; // "tip"

關鍵差異場景

1. href / src:Property 返回絕對 URL,Attribute 返回原始值

<a id="a" href="/path">
a.href;           // "https://domain.com/path" (解析後絕對路徑)
a.getAttribute('href'); // "/path" (HTML 原始值)

2. value (輸入框):單向同步 Attribute → Property

<input value="init">
el.setAttribute('value', 'new'); // attribute & property 都變 'new'
el.value = 'user input';         // property 變 'user input', attribute 仍為 'new' (原始值)
// 用途:通過 attribute 獲取初始值實現重置功能

3. style / 事件處理器:返回類型不同

el.style;           // CSSStyleDeclaration 對象
el.getAttribute('style'); // "color: red;" 字符串

el.onclick;         // Function 對象
el.getAttribute('onclick'); // "handler()" 字符串

4. Boolean 屬性

<input checked>
el.checked;                    // true (Boolean)
el.getAttribute('checked');    // "" (空字符串, 存在即 true)
el.hasAttribute('checked');    // true (推薦檢測方式)

瀏覽器兼容性陷阱 (IE8-)

  • getAttribute/setAttribute 可互訪 property,大小寫不敏感導致衝突:
// IE8 兼容模式
document.body.abba = 1;
document.body.ABBA = 5;
document.body.getAttribute('ABba'); // 返回 1 (首次出現的值),而非 5

最佳實踐指南

  1. 98% 場景用 Property:el.id、el.className、el.value、el.checked、el.style.color、el.dataset.xxx。
  2. 必須用 Attribute 時:
    • 自定義屬性 (非標準):el.getAttribute('data-x') / el.dataset.x (HTML5 推薦)。
    • 獲取原始 href/src/value 未解析值。
    • 檢測 Boolean 屬性存在性:el.hasAttribute('disabled')。
    • SVG 元素屬性 (如 viewBox)。
  3. jQuery 統一:.prop() 操作 Property,.attr() 操作 Attribute,.data() 操作 data-* 緩存 (不同步到 DOM)。
copyright © 萬盛學電腦網 all rights reserved