我想使用纯 javascript 检查 HTML5 数据属性是否存在。 我已经尝试了下面的代码片段,但它不起作用。
if(object.getAttribute("data-params")==="undefined") {
//data-attribute doesn't exist
}
最佳答案
Element.getAttribute
如果属性不存在,则返回 null
或空字符串。
你会使用 Element.hasAttribute
:
if (!object.hasAttribute("data-example-param")) {
// data attribute doesn't exist
}
或Element.dataset
(另请参阅:in
operator):
if (!("exampleParam" in object.dataset)) {
// data attribute doesn't exist
}
甚至
if (!object.getAttribute("data-example-param")) {
// data attribute doesn't exist or is empty
}
关于javascript - 如何使用普通 javascript 检查数据属性是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32249997/