一、'表親戚':attribute和property
為什么稱attribute和property為'表親戚'呢?因為他們既有共同處,也有不同點.
attribute
是 dom 元素在文檔中作為 html 標簽擁有的屬性;
property
是 dom 元素在 js 中作為對象擁有的屬性。
從定義上可以看出:
- 對於 html 的標准屬性來說,attribute 和 property 是同步的,是會自動更新的
- 但是對於自定義的屬性來說,他們是不同步的.(自定義屬性不會自動添加到property)
- property 的值可以改變;attribute 的值不能改變
二、 兩者輸出形式
- 分別打印兩個值
打印attribute屬性
//html
<div class="divClass" id="divId" ></div>
//js
window.onload = function(){
var divId = document.getElementById('divId');
console.log(divId.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
發現上面兩組值是相等的.
雖然都可以取值,但《js高級程序設計》中提到,為了方便操作,建議大家用setAttribute()和getAttribute()來操作即可。
打印property
html自帶的dom屬性會自動轉換成property,但是自定義的屬性沒有這個'權利'
直接把div標簽當作對象,用'.'輸出即是property屬性
但是注意!property是不能輸出自定義屬性的
<div class="divClass" id="divId" addUserDefine="zidingyi"></div>
console.log(divId.class); //打印 divClass
console.log(divId.addUserDefine) //打印 undefined
打開Elements的properties可以看到,dom存在的屬性,property同樣繼承了,而addUserDefine
卻沒有出現在property中
property:
var obj = {};
Object.defineProperty(obj,'name',{
value:'Property'
})
console.log(obj.name) //打印 Property
三、用例子解析兩者賦值
如果我們修改了property的值
//html
<input value="initValue" id="ipt"/>
//js
window.onload = function(){
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
我們再來看看input的值
難以置信?
我們再來看看從修改attribute入手
//html
<input value="initValue" id="ipt"/>
//js
window.onload = function(){
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
總結如下:
- property比attribute'霸道',估計是'表哥'
- property和attribute兩者是屬於單方面通信,即:
1.property能夠從attribute中得到同步;
2.attribute不會同步property上的值;
再啰嗦一句:
對屬性Property可以賦任何類型的值,而對特性Attribute只能賦值字符串!
//js
var obj = {
value : false,
}
var ipt = document.getElementById('ipt');
obj.value = true; //property更改
ipt.setAttribute('value',true) //attribute更改
console.log(typeof obj.value); //boolean
console.log(obj.value) //true
console.log(typeof ipt.value) //string
console.log(ipt.value); //true
大吉大利,感謝閱讀,歡迎糾正!