Description
前言
对于attributes和properties这两个。经常弄混淆。所以想总结一下。
文章链接1
stackoverflow关于这个问题的讨论
文章链接2
Property
每一个DOM节点,都是一个对象。像其他JS对象一样,DOM节点这类型HTMLElement对象,也可以添加一些方法或者属性。
这些自定义添加的属性,就是property。它只能被JS所读取,并不会影响HTML的展示。(它能被JS的for-in方法遍历出来,但innerHTML里面不会显示)
Attribute
与Property不同,Attribute会DOM节点上显示出来,但不会在DOM对象中被for-in遍历出来。
例如上图的input标签,他的Attributies包括value,type,name,id。
想操作DOM元素的的attribute,得依靠下列的JS方法:
elem.hasAttribute(name);// 判断是否存在
elem.getAttribute(name);// 获取该Attribute的值
elem.setAttribute(name, value);// 写入该Attribute的值
elem.removeAttribute(name);// 删除该Attribute
需要注意的是
- 由于Attribute会显示在DOM上面,所以它的键名不区分大小写
- 它的值只可以是字符串
Attribute与Property之间的区别
- 于build-in属性,attribute和property共享数据,attribute更改了会对property造成影响,反之亦然,但是两者的自定义属性是独立的数据,即使name一样,也互不影响,看起来是下面这张图,但是IE6、7没有作区分,依然共享自定义属性数据
-
并不是所有的attribute与对应的property名字都一致,比如attribute 的class属性,使用property操作的时候应该是这样className
-
对于值是true/false的property,类似于input的checked attribute等,attribute取得值是HTML文档字面量值,property是取得计算结果,property改变并不影响attribute字面量,但attribute改变会一向property计算
<input id="test3" type="checkbox"/>
var t=document.getElementById('test3');
console.log(t.getAttribute('checked'));//null
console.log(t.checked);//false;
t.setAttribute('checked','checked');
console.log(t.getAttribute('checked'));//checked
console.log(t.checked);//true
t.checked=false;
console.log(t.getAttribute('checked'));//checked
console.log(t.checked);//false
- 对于一些和路径相关的属性,两者取得值也不尽相同,但是同样attribute取得是字面量,property取得是计算后的完整路径
<a id="test4" href="#">Click</a>
var t=document.getElementById('test4');
console.log(t.getAttribute('href'));//#
console.log(t.href);//file:///C:/Users/bsun/Desktop/ss/anonymous.html#
然而关于checked 属性需要记住的最重要的一点是:它和checked property并不是一致的。实际上这个attribute和defaultChecked property一致,而且只应该用来设置checkbox的初始值。checked attribute并不随着checkedbox的状态而改变,但是checked property却跟着变。因此浏览器兼容的判断checkebox是否被选中应该使用property
if ( elem.checked )
if ( $( elem ).prop( "checked" ) )
if ( $( elem ).is( ":checked" ) )
这对其它一些类似于selected、value这样的动态attribute也适用。
Attribute与Property之间的同步
所有的DOM节点对象,都有一套标准的properties 。这些DOM对象的标准properties,会自动与其attributes同步。例如id\title\lang\dir\className
document.body.setAttribute('id','la-la-la'):
alert(document.body.id); // la-la-la
但有的properties与attributes的同步值,却并不是一样的
自动同步,但值并不完全相等。例如表单元素input的checked属性。
只能从Attribute单向同步到Property
例如:表单元素input的value属性。
从Attribute同步到Property
Property却不能同步到Attribute
IE
- 在IE6\7\8里面,propertites与attributies是自动同步的,并且attributies的值不限于字符串。
- 在IE6\7里面,propertites与attributies的键名不区分大小写。
总结
Properties就是JavaScript对象中的一个属性,而Attribute则是HTML元素中的一个属性。
Properties | Attribute |
---|---|
值可以任意类型的值 | 值只能是字符串 |
键名区分大小写 | 键名不区分大小写 |
在innerHTML里面不可见 | 在innerHTML里面可见 |
标准的DOM Properties会自动与Attributies同步,自定义的则不会