javascript中attribute和property的區別詳解

這篇文章主要介紹了javascript中attribute和property的區別詳解,attribute和property對新手來講,特別容易混淆概念,本文就清晰的講解了它們的區別,須要的朋友能夠參考下javascript

DOM元素的attribute和property很容易混倄在一塊兒,分不清楚,二者是不一樣的東西,可是二者又聯繫緊密。不少新手朋友,也包括之前的我,常常會搞不清楚。java

attribute翻譯成中文術語爲「特性」,property翻譯成中文術語爲「屬性」,從中文的字面意思來看,確實是有點區別了,先來講說attribute。數組

attribute是一個特性節點,每一個DOM元素都有一個對應的attributes屬性來存放全部的attribute節點,attributes是一個類數組的容器,說得準確點就是NameNodeMap,總之就是一個相似數組但又和數組不太同樣的容器。attributes的每一個數字索引以名值對(name=」value」)的形式存放了一個attribute節點。瀏覽器

複製代碼 代碼以下:翻譯

<div class="box" id="box" gameid="880">hello</div>

上面的div元素的HTML代碼中有class、id還有自定義的gameid,這些特性都存放在attributes中,相似下面的形式:code

複製代碼 代碼以下:對象

[ class="box", id="box", gameid="880" ]

能夠這樣來訪問attribute節點:索引

複製代碼 代碼以下:ip

var elem = document.getElementById( 'box' );
console.log( elem.attributes[0].name ); // class
console.log( elem.attributes[0].value ); // box

可是IE6-7將不少東西都存放在attributes中,上面的訪問方法和標準瀏覽器的返回結果又不一樣。一般要獲取一個attribute節點直接用getAttribute方法:rem

複製代碼 代碼以下:

console.log( elem.getAttribute('gameid') ); // 880

要設置一個attribute節點使用setAttribute方法,要刪除就用removeAttribute:

複製代碼 代碼以下:

elem.setAttribute('testAttr', 'testVal');
console.log( elem.removeAttribute('gameid') ); // undefined

attributes是會隨着添加或刪除attribute節點動態更新的。

property就是一個屬性,若是把DOM元素當作是一個普通的Object對象,那麼property就是一個以名值對(name=」value」)的形式存放在Object中的屬性。要添加和刪除property也簡單多了,和普通的對象沒啥分別:

複製代碼 代碼以下:

elem.gameid = 880; // 添加
console.log( elem.gameid ) // 獲取
delete elem.gameid // 刪除

之因此attribute和property容易混倄在一塊兒的緣由是,不少attribute節點還有一個相對應的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節點,或者自定義property,二者就沒有關係了。

複製代碼 代碼以下:

console.log( elem.getAttribute('gameid') ); // 880
console.log( elem.gameid ); // undefined
elem.areaid = '900';
console.log( elem.getAttribute('areaid') ) // null

對於IE6-7來講,沒有區分attribute和property:

複製代碼 代碼以下:

console.log( elem.getAttribute('gameid') ); // 880
console.log( elem.gameid ); // 880
elem.areaid = '900';
console.log( elem.getAttribute('areaid') ) // 900

不少新手朋友估計都很容易掉進這個坑中。

DOM元素一些默認常見的attribute節點都有與之對應的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節點,只有存在該節點,對應的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


最後爲了更好的區分attribute和property,基本能夠總結爲attribute節點都是在HTML代碼中可見的,而property只是一個普通的名值對屬性。

複製代碼 代碼以下:

// gameid和id都是attribute節點
// id同時又能夠經過property來訪問和修改
<div gameid="880" id="box">hello</div>
// areaid僅僅是property
elem.areaid = 900;
相關文章
相關標籤/搜索