一、'表親戚':attribute和property
為什么稱attribute和property為'表親戚'呢?因為他們既有共同處,也有不同點.
attribute 是 dom 元素在文檔中作為 html 標簽擁有的屬性;
property 是 dom 元素在 js 中作為對象擁有的屬性。
從定義上可以看出:
二、 兩者輸出形式
1、分別打印兩個值
打印attribute屬性
//html<div class="divClass" id="divId" ></div>//jswindow.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')) //打印divClassconsole.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); //打印 divClassconsole.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"/>//jswindow.onload = function(){ var ipt = document.getElementById('ipt'); ipt.value = 'changeValue' console.log(ipt.value); console.log(ipt.getAttribute('value'));}猜一下結果??
答案是:
console.log(ipt.value); //changeValueconsole.log(ipt.getAttribute('value')); //initValue我們再來看看input的值

難以置信?
我們再來看看從修改attribute入手
//html<input value="initValue" id="ipt"/>//jswindow.onload = function(){ var ipt = document.getElementById('ipt'); ipt.setAttribute('value','changeValue') console.log(ipt.value); console.log(ipt.getAttribute('value'));}輸出:
console.log(ipt.value); //changeValueconsole.log(ipt.getAttribute('value')); //changeValue總結如下:
1.property能夠從attribute中得到同步;
2.attribute不會同步property上的值;
再 主站蜘蛛池模板: 东安县| 呼图壁县| 芷江| 朝阳市| 望谟县| 龙口市| 揭阳市| 吉安市| 望谟县| 都匀市| 莱西市| 鄂托克前旗| 陆良县| 威宁| 柳林县| 开封县| 新干县| 霸州市| 郑州市| 怀仁县| 西乌珠穆沁旗| 平舆县| 永川市| 射阳县| 包头市| 颍上县| 曲水县| 广灵县| 蕲春县| 武定县| 广平县| 高邑县| 云龙县| 巴青县| 济宁市| 饶河县| 雷山县| 广河县| 连州市| 丰镇市| 赣州市|