HTML attribute vs. DOM property - 一种豁然开朗的感觉

用醍醐灌顶来形容也不过分。一直以来在使用jQuery操作dom是如果使用attr不能修改元素的值,就换prop,但是从来也没有深究过原因。今天在阅读angular的文档时遇见了以下说明,真是让人豁然开朗。



HTML attribute vs. DOM property

The distinction between an HTML attribute and a DOM property is crucial to understanding how Angular binding works.

Attributes are defined by HTML. Properties are defined by the DOM (Document Object Model).

  • A few HTML attributes have 1:1 mapping to properties. id is one example.

  • Some HTML attributes don't have corresponding properties. colspan is one example.

  • Some DOM properties don't have corresponding attributes. textContent is one example.

  • Many HTML attributes appear to map to properties ... but not in the way we might think!

That last category can be especially confusing ... until we understand this general rule:

Attributes initialize DOM properties and then they are done. Property values can change; attribute values can't.

For example, when the browser renders <input type="text" value="Bob">, it creates a corresponding DOM node with a value propertyinitialized to "Bob".

When the user enters "Sally" into the input box, the DOM element value property becomes "Sally". But the HTML value attribute remains unchanged as we discover if we ask the input element about that attribute: input.getAttribute('value') // returns "Bob"

The HTML attribute value specifies the initial value; the DOM value property is the current value.

The disabled attribute is another peculiar example. A button's disabled property is false by default so the button is enabled. When we add the disabled attribute, its presence alone initializes the button's disabled property to true so the button is disabled.

Adding and removing the disabled attribute disables and enables the button. The value of the attribute is irrelevant, which is why we cannot enable a button by writing <button disabled="false">Still Disabled</button>.

Setting the button's disabled property (say, with an Angular binding) disables or enables the button. The value of the property matters.

The HTML attribute and the DOM property are not the same thing, even when they have the same name.


原文地址:https://angular.io/docs/ts/latest/guide/template-syntax.html


举个列子:我们都是用$('xxx').prop('checked',true)来选中checkbox,而不是$('xxx').attr('checked',true);后者没有作用的。正像上面文章说的attribute决定初始值,property决定当前值。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值