1:概念:
自定義屬性是H5新增的功能,最初的設計初衷是爲了記錄頁面中的一些信息,比如一個按鈕的點擊次數等等.
2語法:
data-attribute 其中attribute可以是傳統的數字,字母下劃線,也可以是dash (-
), dot (.
), colon (:
).
注意:若attribute是大寫字母的話,會出現一些不同,下文會說明
3:獲取自定義屬性值的方法:
A:Dom獲取,即getAttrtibute
document.getElementById('').getAttribute('data-attribute');
這種方法是萬能的,不會出現任何問題,可以獲取元素的其他屬性
B:H5提供了專用的方法即ele.dataset.attribute
<div class="div1" data-index="1"></div>
獲取則爲:document.getElementByClassName('div1')[0].dataset.index //111
但是當attrtibute爲大寫字母時則無法獲取該屬性
<div class="div1" data-Do="hello"></div>
var div1=document.getElementsByClassName('div1')[0];
console.log(div1.getAttribute('data-Do')); //undefined
總結:getAtrtribute獲取的兼容性更高,不僅可以獲取自定義屬性,還可以獲取其他屬性
ele.dataset.attr的方法屬性值不能爲大寫字母,並且是爲獲取data-屬性設計的專用獲取方法.