HTML DOM的attribute和property

概念

attribute:特性,property:属性,attribute 是元素标签的属性,property 是元素对象的属性;
attribute是HTML标签上的特性,它的值只能够是字符串;
property是DOM中的属性,是JavaScript里的对象;

例子

attribute是我们在html代码中经常看到的键值对
下面代码中的 input 节点有三个 attribute:
id:myinput
type:text
value:myvalue

	<input id="myinput" type="text" value="myvalue" />

property是attribute对应的DOM节点的对象属性:

	HTMLInputElement.id === 'myinput'
	HTMLInputElement.type === 'text'
	HTMLInputElement.value === 'myvalue'

区别

	<input id="myinput" type="text1" value="myvalue" /> 
	//页面加载完成后 在这个input中输入 Bob 

注意这段代码中的type属性,我们给的值是text1,这并不属于input支持的type种类,HTML ‘input’ 标签

让我们来看看上面这个 input 节点的attribute和property的:

	//attribute
	input.getAttribute('id')  //myinput
	input.getAttribute('type') //text1
	input.getAttribute('value') //Bob

	//property
	input.id   //myinput
	input.type //text
	input.value //Bob

可以看到,在 attribute 中,值仍然是 html 代码中的值。而在 property 中,type被修改为text,而value随着用户改变 input 的输入,也变更为了 Bob

总结

property能够从attribute中得到同步;
attribute不会同步property上的值;
attribute和property之间的数据绑定是单向的,attribute->property;
更改property和attribute上的任意值,都会将更新反映到HTML页面中;

来源于网络:
创建

  • DOM对象初始化时会创建默认的基本property;
  • 只有在HTML标签中定义的attribute才会被保存在property的attributes属性中;
  • attribute会初始化property中的同名属性,但自定义的attribute不会出现在property中;
  • attribute的值都是字符串;

数据绑定

  • attributes的数据会同步到property上,然而property的更改不会改变attribute;
    对于value,class这样的属性/特性,数据绑定的方向是单向的,attribute->property;
  • 对于id而言,数据绑定是双向的,attribute<=>property;
  • 对于href而言,二者是双向绑定的,property中的href永远保存绝对路径,而attribute中的href则是保存相对路径。
  • 对于disabled而言,改变attributes中的disabled不会改变更改property,也不会取消输入栏的禁用效果。当property上的disabled为false时,attribute上的disabled必定会不存在,此时数据绑定可以认为是双向的;

使用

  • 可以使用DOM的setAttribute方法来同时更改attribute和property;
  • 更改property和attribute上的任意值,都会将更新反映到HTML页面中;
  • 直接访问attributes上的值会得到一个Attr对象,而通过getAttribute方法访问则会直接得到attribute的值;
  • 大多数情况(除非有浏览器兼容性问题),jQuery.attr是通过setAttribute实现,而jQuery.prop则会直接访问DOM对象的property;

关键的两句话:

  • attribute(特性),是我们赋予某个事物的特质或对象。
  • property(属性),是早已存在的不需要外界赋予的特质。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值