javascript中attribute和property的區(qū)別詳解
DOM元素的attribute和property很容易混倄在一起,分不清楚,兩者是不同的東西,但是兩者又聯系緊密。很多新手朋友,也包括以前的我,經常會搞不清楚。
attribute翻譯成中文術語為“特性”,property翻譯成中文術語為“屬性”,從中文的字面意思來看,確實是有點區(qū)別了,先來說說attribute。
attribute是一個特性節(jié)點,每個DOM元素都有一個對應的attributes屬性來存放所有的attribute節(jié)點,attributes是一個類數組的容器,說得準確點就是NameNodeMap,總之就是一個類似數組但又和數組不太一樣的容器。attributes的每個數字索引以名值對(name=”value”)的形式存放了一個attribute節(jié)點。
上面的div元素的HTML代碼中有class、id還有自定義的gameid,這些特性都存放在attributes中,類似下面的形式:
可以這樣來訪問attribute節(jié)點:
var elem = document.getElementById( 'box' );
console.log( elem.attributes[0].name ); // class
console.log( elem.attributes[0].value ); // box
但是IE6-7將很多東西都存放在attributes中,上面的訪問方法和標準瀏覽器的返回結果又不同。通常要獲取一個attribute節(jié)點直接用getAttribute方法:
要設置一個attribute節(jié)點使用setAttribute方法,要刪除就用removeAttribute:
console.log( elem.removeAttribute('gameid') ); // undefined
attributes是會隨著添加或刪除attribute節(jié)點動態(tài)更新的。
property就是一個屬性,如果把DOM元素看成是一個普通的Object對象,那么property就是一個以名值對(name=”value”)的形式存放在Object中的屬性。要添加和刪除property也簡單多了,和普通的對象沒啥分別:
elem.gameid = 880; // 添加
console.log( elem.gameid ) // 獲取
delete elem.gameid // 刪除
之所以attribute和property容易混倄在一起的原因是,很多attribute節(jié)點還有一個相對應的property屬性,比如上面的div元素的id和class既是attribute,也有對應的property,不管使用哪種方法都可以訪問和修改。
console.log( elem.getAttribute('id') ); // box
console.log( elem.id ); // box
elem.id = 'hello';
console.log( elem.getAttribute('id') ); // hello
但是對于自定義的attribute節(jié)點,或者自定義property,兩者就沒有關系了。
console.log( elem.getAttribute('gameid') ); // 880
console.log( elem.gameid ); // undefined
elem.areaid = '900';
console.log( elem.getAttribute('areaid') ) // null
對于IE6-7來說,沒有區(qū)分attribute和property:
console.log( elem.getAttribute('gameid') ); // 880
console.log( elem.gameid ); // 880
elem.areaid = '900';
console.log( elem.getAttribute('areaid') ) // 900
很多新手朋友估計都很容易掉進這個坑中。
DOM元素一些默認常見的attribute節(jié)點都有與之對應的property屬性,比較特殊的是一些值為Boolean類型的property,如一些表單元素:
<input type="radio" checked="checked" id="raido">
var radio = document.getElementById( 'radio' );
console.log( radio.getAttribute('checked') ); // checked
console.log( radio.checked ); // true
對于這些特殊的attribute節(jié)點,只有存在該節(jié)點,對應的property的值就為true,如:
<input type="radio" checked="anything" id="raido">
var radio = document.getElementById( 'radio' );
console.log( radio.getAttribute('checked') ); // anything
console.log( radio.checked ); // true
最后為了更好的區(qū)分attribute和property,基本可以總結為attribute節(jié)點都是在HTML代碼中可見的,而property只是一個普通的名值對屬性。
// gameid和id都是attribute節(jié)點
// id同時又可以通過property來訪問和修改
<div gameid="880" id="box">hello</div>
// areaid僅僅是property
elem.areaid = 900;
相關文章
javascript 進階篇1 正則表達式,cookie管理,userData
接下來開始我們的進階之路,更實用的技巧分享2012-03-03