[英]Native JS for Reading HTML5 Custom Data Attributes
我了解到HTML5包含一種使用數據前綴在元素上設置自定義屬性的方法。 但是,在javascript代碼塊中如何讀取屬性方面我有點神秘。 我想這是我對DOMStringMap如何工作的解釋。
有人可以簡化如何閱讀以下示例html的屬性。
<span data-complex-key="howtoRead" data-id="anId">inner</span>
嘗試以下並沒有按預期工作
spanEl.dataset['id'] // straight-forward and result is anId
spanEl.dataset['complex-key'] // undefined
spanEl.dataset['complex']['key'] // throws 'cannot read property of undefined'
spanEl.getAttribute('complex-key') // there's a null however,
spanEl.getAttribute('data-complex-key') // this variant seems to work
讓我想知道的另一件事是,CSS選擇器似乎遵循與我在DOM中編寫的精確相同的模式,那么為什么這不是從javascript讀取的情況。
例如,這將匹配
span[data-complex-key="howtoRead"] { color:green }
欣賞幫助,仍然越來越多地使用HTML5 Canvas,Video和本地數據存儲:)
在vanilla-JS中,假設spanEl
是對DOM節點的引用
spanEl.dataset.complexKey
當您的數據屬性包含超量( -
)時,將使用camelCase
表示法(請參閱http://jsbin.com/oduguw/3/edit )
spanEl.getAttribute('data-complex-key')
你已經注意到會好起來的。 作為旁注,在jQuery中,您可以使用訪問該data
屬性
$(spanEl).data("complex-key")
在Chrome中,它似乎以一種不那么直接的方式映射數據鍵:
console.log(spanEl.dataset);
//shows:
//DOMStringMap
// complexKey: "howtoRead"
// id: "anId"
它將“complex-key”轉換為“complexKey”。
雖然不是完全直截了當,但這種行為在HTML5規范中定義:
http://dev.w3.org/html5/spec//global-attributes.html#dom-dataset
您的第一個和最后一個方法是正確的,而不使用任何庫。 但是,帶減號的鍵會轉換為Camel Case,因此complex-key會變為complexKey:
spanEl.dataset['id']
spanEl.dataset['complexKey']
spanEl.getAttribute('data-complex-key')
但是,只有最后一個在IE中工作到9個。(我不知道10個。)數據屬性只不過是在這種情況下具有命名約定的普通屬性。
spanEl.dataSet["complexKey"]
//使用jQuery你可以嘗試這個
$('span').data('complex-key') // Will give you **howtoRead**
$('span').data('id') // Will give you **anId**
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.