用于读取HTML5自定义数据属性的本机JS

时间:2012-09-26 16:34:08

标签: javascript html5

我了解到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,视频和本地数据存储:)

4 个答案:

答案 0 :(得分:8)

在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")

答案 1 :(得分:2)

在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

答案 2 :(得分:1)

不使用任何库时,您的第一个和最后一个方法是正确的。但是,带减号的键将转换为Camel Case,因此complex-key变为complexKey:

spanEl.dataset['id']
spanEl.dataset['complexKey']
spanEl.getAttribute('data-complex-key')

但是,只有最后一个在IE中工作到9个。(我不知道10个。)数据属性只不过是具有命名约定的普通属性。

答案 3 :(得分:0)

 spanEl.dataSet["complexKey"]   

//使用jQuery,你可以尝试这个

 $('span').data('complex-key')  // Will give you **howtoRead**

    $('span').data('id')  // Will give you **anId**