JS中的“特性”與“屬性” attribute與property
阿新 • • 發佈:2019-02-02
DOM元素的attribute和property很容易混倄在一起,分不清楚。特別區分一下。
- attribute是HTML標籤上的"特性",它的值只能夠是字串
- property是DOM中的"屬性",是JavaScript裡的物件;
attribute節點都是在HTML程式碼中可見的,而property只是一個普通的名值對屬性。
之所以attribute和property容易混倄在一起的原因是,很多attribute節點還有一個相對應的property屬性,比如div元素的id和class既是attribute,也有對應的property,不管使用哪種方法都可以訪問和修改。
但是對於自定義的attribute節點,或者自定義property,兩者就沒有關係了。
例如:
1、<div class="box" id="box" gameid="880">hello</div>
其中,gameid自定義屬性,因此只能用getAttribute訪問,無法用e.propName訪問
console.log( elem.getAttribute('gameid') ); // 880
console.log(elem.gameid); //undefined
console.log( elem.removeAttribute('gameid') ); // undefined 刪除
2、自定義property節點
elem.myColor = “red”; // 新增
console.log( elem.myColor ) // “red”
console.log(elem.getAttribute('myColor')); //null
delete elem.myColor // 刪除