繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM