我了解到 HTML5 包含一种使用 data- 前缀在元素上设置自定义属性的方法。但是,对于如何在 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、视频和本地数据存储:)
最佳答案
在 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")
关于javascript - 原生 JS 读取 HTML5 自定义数据属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12606367/