JS中DOM元素的attribute与property
定义的区别
- attribute
1.是dom元素在文档中作为html标签拥有的属性;
2.其值不能改变
3.只能赋值为字符串 - prototype
1.是dom元素在js中作为对象拥有的属性
2.其值可以改变
3.可以赋任何类型的值
以上是较浅的区别,以下继续深入探讨
对比二者的使用
//html
<div class="divClass" id="divId"></div>
//javascript
var divId = document.getElementById('divId');
console.log(divId.attributes);
此时会打印出它的attributes对象(如下图):
此时让我们对attributes对象的值进行查看
console.log(divId.attributes[0]); //打印 class="divClass"
console.log(divId.attributes.class) //打印 class="divClass"
console.log(divId.getAttribute('class')) //打印divClass
console.log(divId.getAttribute('id')) //打印divId
可以看出两组的值相等。
html自带的dom属性会自动转化成prototype,这里可以把标签div看作一个对象,使用’.'来输出即为protopyte属性。
但是不包含自定义属性,既prototype不能输出自定义属性。
<div class="divClass" id="divId" addArrt="add"></div>
console.log(divId.class); //打印 divClass
console.log(divId.addArrt) //打印 undefined
可以看出prototype,dom存在的属性,property同样继承了,而addArrt却没有出现在property中
案例剖析
让我们来修改prototype
//html
<input value="initValue" id="ipt"/>
//js
var ipt = document.getElementById('ipt');
ipt.value = 'changeValue'
console.log(ipt.value);
console.log(ipt.getAttribute('value'));
先自己判断一下打印的值。
当当当当!!!
真正的答案揭晓:
console.log(ipt.value); //changeValue
console.log(ipt.getAttribute('value')); //initValue
现在再来看看修改attritube会怎么样
//html
<input value="initValue" id="ipt"/>
//js
var ipt = document.getElementById('ipt');
ipt.setAttribute('value','changeValue')
console.log(ipt.value);
console.log(ipt.getAttribute('value'));
输出如下:
console.log(ipt.value); //changeValue
console.log(ipt.getAttribute('value')); //changeValue
分析了这么多,来总结一下:
创建
- DOM对象初始化时会在创建默认的基本property;
- 只有在HTML标签中定义的attribute才会被保存在property的attributes属性中;
- attribute会初始化property中的同名属性,但自定义的attribute不会出现在property中;
- attribute的值都是字符串;
数据绑定 - attributes的数据会同步到property上,然而property的更改不会改变attribute;
- 对于value,class这样的属性/特性,数据绑定的方向是单向的,attribute->property;
- 对于id而言,数据绑定是双向的,attribute<=>property;
- 对于disabled而言,property上的disabled为false时,attribute上的disabled必定会并存在,此时数据绑定可以认为是双向的;
使用 - 可以使用DOM的setAttribute方法来同时更改attribute;
- 直接访问attributes上的值会得到一个Attr对象,而通过getAttribute方法访问则会直接得到attribute的值;
- 大多数情况(除非有浏览器兼容性问题),jQuery.attr是通过setAttribute实现,而jQuery.prop则会直接访问DOM对象的property;
文章参考:here