DIV CSS 佈局教程網

JavaScript中attribute與property的區別詳解
編輯:JavaScript基礎知識     

DOM元素的 attribute 與 property 很容易混淆,兩者是不同的東西,但又緊密聯繫,很多新手(包括以前的我)經常搞不清楚。

attribute 譯為「特性」,property 譯為「屬性」,從字面看確實有點區別。

attribute(特性)

attribute 是一個特性節點,每個DOM元素都有一個對應的 attributes 屬性來存放所有 attribute 節點。attributes 是一個類陣列的容器(準確地說是 NameNodeMap),每個數字索引以名值對(name="value")形式存放一個 attribute 節點。

復制代碼 代碼如下:<div class="box" id="box" gameid="880">hello</div>

上面 div 的 class、id 與自訂的 gameid 都存放在 attributes 中,類似:[ class="box", id="box", gameid="880" ]。可以這樣存取:

復制代碼 代碼如下:
var elem = document.getElementById( 'box' );
console.log( elem.attributes[0].name ); // class
console.log( elem.attributes[0].value ); // box

(IE6-7 把很多東西都放進 attributes,返回結果與標準瀏覽器不同。)通常取得屬性節點直接用 getAttribute:

復制代碼 代碼如下:console.log( elem.getAttribute('gameid') ); // 880

設定用 setAttribute,刪除用 removeAttribute。attributes 會隨著節點增刪動態更新。

property(屬性)

property 就是一個屬性,如果把DOM元素看成普通 Object,那麼 property 就是以名值對形式存放在其中的屬性。新增與刪除很簡單,跟普通物件沒啥分別:

復制代碼 代碼如下:
elem.gameid = 880; // 新增
console.log( elem.gameid ) // 取得
delete elem.gameid // 刪除

為何容易混淆

很多 attribute 節點還有一個對應的 property,比如 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,兩者取值互通。

布爾屬性的特殊性

一些表單元素的屬性值為Boolean類型,比較特殊:

復制代碼 代碼如下:
<input type="radio" checked="checked" id="radio">
var radio = document.getElementById( 'radio' );
console.log( radio.getAttribute('checked') ); // checked
console.log( radio.checked ); // true

對於這些屬性,只要存在該節點,對應 property 的值就為 true:

復制代碼 代碼如下:
<input type="radio" checked="anything" id="radio">
var radio = document.getElementById( 'radio' );
console.log( radio.getAttribute('checked') ); // anything
console.log( radio.checked ); // true

總結:attribute 節點都是在HTML代碼中可見的,而 property 只是一個普通的名值對屬性。

復制代碼 代碼如下:
// gameid 和 id 都是 attribute 節點
// id 同時又可透過 property 存取和修改
<div gameid="880" id="box">hello</div>
// areaid 僅僅是 property
elem.areaid = 900;

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved