天天看点

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)是不一样的,尽管它们都叫属性。