前端雜談: Attribute VS Property
attribute是我們在html 程式碼中經常看到的鍵值對, 例如:
<input id="the-input" type="text" value="Name:" /> 複製程式碼
上面程式碼中的 input 節點有三個 attribute:
- id : the-input
- type : text
- value : Name:
property是 attribute 對應的 DOM 節點的 物件屬性 (Object field), 例如:
HTMLInputElement.id === 'the-input' HTMLInputElement.type === 'text' HTMLInputElement.value === 'Name:' 複製程式碼
第二個問題:
從上面的例子來看, 似乎 attribute 和 property 是相同的, 那麼他們有什麼區別呢?
讓我們來看另一段程式碼:
<input id="the-input" type="typo" value="Name:" /> // 在頁面載入後, 我們在這個input中輸入 "Jack" 複製程式碼
注意這段程式碼中的 type 屬性, 我們給的值是typo , 這並不屬於 input 支援的 type 種類.
讓我們來看看上面這個 input 節點的 attribute 和 property:
// attribute still remains the original value input.getAttribute('id') // the-input input.getAttribute('type') // typo input.getAttribute('value') // Name: // property is a different story input.id // the-input input.type //text input.value // Jack 複製程式碼
可以看到, 在 attribute 中, 值仍然是 html 程式碼中的值. 而在 property 中, type 被自動修正為了text , 而 value 隨著使用者改變 input 的輸入, 也變更為了Jack
這就是 attribute 和 Property 間的區別:
attribute 會始終保持 html 程式碼中的初始值, 而 Property 是有可能變化的.
其實, 我們從這兩個單詞的名稱也能看出些端倪:
attribute從語義上, 更傾向於不可變更的
而property 從語義上更傾向於在其生命週期中是可變的
Attribute or Property 可以自定義嗎?
先說結論:attribute 可以 property 不行
我們可以嘗試在 html 中自定義 attribute:
<input value="customInput" customeAttr="custome attribute value" /> 複製程式碼
然後我們嘗試獲取自定義的屬性:
input.getAttribute('customAttr') // custome attribute value input.customAttr // undefined 複製程式碼
可以看到, 我們能夠成功的獲取自定義的 attribute, 但是無法獲取 property.
其實不難理解, DOM 節點在初始化的時候會將html 規範 中定義的 attribute 賦值到 property 上, 而自定義的 attribute 並不屬於這個氛圍內, 自然生成的 DOM 節點就沒有這個 property.
一些補充
需要注意, 有一些特殊的 attribute, 它們對應的 Property 名稱會發生改變, 比如:
- for (attr) => htmlFor (prop)
- class (attr) => className (prop)
(如果我們追到 DOM 的原始碼中, 應該是能列出一份清單的: 哪些 attribute 的名稱會對應到哪些 Property, 感興趣不妨試試)
關於 attribute 和 property 兩者之間的差別, stackoverflow 上有一些很有意思的討論:
ofollow,noindex">stackoverflow.com/a/6377829/5…
其中有些人認為 attribute 的值表示的是 defaultValue, 而 DOM 節點的 Property 則是另一回事. 比如: check (attr) 對應的是 defaultChecked (prop), value(attr) 對應的應該是 defaultValue (prop)
關於我們在 attribute 中 value 的限制 (如 input 的 type 有那些有效值), 可以參考這個連結: