Attribute和Property的区别

比较

  • Attribute

    • HTML元素的“选项|附加项”,格式:名称="值"
    • 值只能为string类型。
    • 如果编辑HTML时设置了元素的attribute值,之后就算改了这个值,attribute依旧是默认的值。
    • 客户端向HTML元素添加的自定义的属性,推荐称为attribute
  • Property

    • JS DOM中,对象的成员(组成部分),所以可以用JS DOM对象访问property(用对象访问成员)。
    • 值类型多样化boolean, string, number等。
  • 区分

    • 位置不同。
      • attribute是HTML中就有的,是元素的选项|附加项。
      • property是JS DOM中有的。是对象的组成|成员。
    • 值类型不同:
      • attribute的值只能是string
      • property因为是对象的成员,类型可多样化(bolean, string, number等)。
    • 其他。
    • (结果)操作他们使用的jQuery方法也不同。
      • jQuery1.6之前,多用attr()
      • 从jQuery1.6开始,区分attributeproperty。对于property使用专门的prop()。其他的使用attr()

boolean attribute

boolean attribute及其规范取值
很特殊的一类attribute。如selected
已知:selected没有在元素的开始标签出现,则元素的selected属性值为false
但如果出现,不论其值为何(空串"",其他字符串值"false", "1", "hhh"),
一旦在开始标签出现,则值为true(或最小化形式,只有单独的名称,无值)。

其他如checked, required, disabled, enabled等,
因为其存在展示的意义实际上是一个boolean值,所以可以将其当做property(值多类型)来读写(使用prop())。

links

JS: attribute vs. property

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).
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值