天天看點

HTML attribute 與 DOM property 的差別

了解Angular綁定是如何工作, 首先要了解HTML attribute 和DOM property的差別。

Attributes由HTML定義。Properties由DOM(文檔對象模型)定義。

  • 一些HTML attributes 是1:1映射到properties的。例如id。
  • 一些HTML attributes 沒有相應的properties。例如colspan。
  • 一些DOM properties 沒有相應的attributes。 例如 textContent。
  • 許多HTML attributes 似乎映射到properties …但不是以你想象的方式!

最後一類比較費解,可以看看這個規則:

Attributes 初始化 DOM properties 之後就沒有關系了。Property 值可以改變, attribute 值不能變。

例如,當浏覽器渲染

<input type="text" value="Bob">

時,它會建立一個對應的DOM節點,其value property已初始化為“Bob”。

當使用者在input中輸入“Sally”時,DOM元素value property變為“Sally”。但是,如果你問有關該元素的attribute,HTML value attribute将保持不變:

HTML value attribute 是初始值; DOM value property是目前值。

disabled attribute是一個特殊的例子。一個button的 disabled property 預設為false,按鈕啟用。當添加disabled attribute時,它的存在會将按鈕的disabled property初始化為true,該按鈕被禁用。

添加/删​​除disabled attribute會禁用/啟用該按鈕。該attribute的值是無關緊要,是以你不能這樣來啟用按鈕

<button disabled =“false”> Still Disabled </ button>

設定按鈕的disabled property(例如,使用Angular綁定)禁用或啟用按鈕。property值是關鍵。

HTML屬性(attribute)和DOM屬性(property)是不一樣的,盡管它們都叫屬性。