比较
-
Attribute
- HTML元素的“选项|附加项”,格式:
名称="值"
。 - 值只能为
string
类型。 - 如果编辑HTML时设置了元素的
attribute
值,之后就算改了这个值,attribute
依旧是默认的值。 - 客户端向HTML元素添加的自定义的属性,推荐称为
attribute
。
- HTML元素的“选项|附加项”,格式:
-
Property
- JS DOM中,对象的成员(组成部分),所以可以用JS DOM对象访问
property
(用对象访问成员)。 - 值类型多样化:
boolean, string, number
等。
- JS DOM中,对象的成员(组成部分),所以可以用JS DOM对象访问
-
区分
- 位置不同。
attribute
是HTML中就有的,是元素的选项|附加项。property
是JS DOM中有的。是对象的组成|成员。
- 值类型不同:
attribute
的值只能是string
。property
因为是对象的成员,类型可多样化(bolean, string, number等
)。
- 其他。
- (结果)操作他们使用的jQuery方法也不同。
- jQuery1.6之前,多用
attr()
。 - 从jQuery1.6开始,区分
attribute
和property
。对于property
使用专门的prop()
。其他的使用attr()
。
- jQuery1.6之前,多用
- 位置不同。
boolean attribute
boolean attribute及其规范取值
很特殊的一类attribute
。如selected
。
已知:selected
没有在元素的开始标签出现,则元素的selected
属性值为false
。
但如果出现,不论其值为何(空串""
,其他字符串值"false", "1", "hhh"
),
一旦在开始标签出现,则值为true
(或最小化形式,只有单独的名称,无值)。
其他如checked, required, disabled, enabled
等,
因为其存在展示的意义实际上是一个boolean
值,所以可以将其当做property
(值多类型)来读写(使用prop()
)。
links
What is a property?
JS DOM objects have properties.
These properties are kind of like instance variables for the particular element.
As such, a property can be different types (boolean, string, etc.).
Properties can be accessed using jQuery’s prop method (as seen below)
and also by interacting with the object in vanilla JS.
As you can see, all of the properties we set in the HTML are available through prop.
Other properties are available too, such as style,
even though we didn’t explicitly set them.
Properties can also be updated through the prop method:
What is an attribute?
Attributes are in the HTML itself, rather than in the DOM.
They are very similar to properties, but not quite as good.
When a property is available it’s recommended that you work with properties
rather than attributes.
An attribute is only ever a string, no other type.
If an element has a default value, the attribute shows the default value
even if the value has changed.
Attributes can be useful when you want to set a custom attribute,
that is, when there is no property associated.
But, to be fair, you can also use custom properties '
(although this might be bad practice).