2015-08-27 63 views
7

我想检查一个HTML5数据属性是否存在使用普通的JavaScript。 我试过下面的代码片段,但它不起作用。如何检查数据属性是否存在与纯JavaScript?

if(object.getAttribute("data-params")==="undefined") { 
    //data-attribute doesn't exist 
} 
+0

'如果(typeof运算的obj [ “数据属性”] == “未定义”){//此处代码}' –

回答

14

Element.getAttribute返回null或空字符串,如果该属性不存在。

你会使用Element.hasAttribute

if (!object.hasAttribute("data-params")) { 
    // data attribute doesn't exist 
} 

Element.dataset(参见:in operator):

if (!("params" in object.dataset)) { 
    // data attribute doesn't exist 
} 

甚至

if (!object.getAttribute("data-params")) { 
    // data attribute doesn't exist or is empty 
} 
+1

为什么作为选择的答案有这个被打上了吗? – Doidgey

0

尝试使用typeof

if(typeof object.getAttribute("data-params") === "undefined") { 
    console.log('data-attribute doesn't exist'); 
} 
1

你苍做到这falsy值检查

if(!object.getAttribute("data-params")) { 
    //data-attribute doesn't exist 
} 

原因getAttribute可以返回null或空字符串

也可以使用object.hasAttribute("data-params")只检查属性是否存在

2

您发布的代码不赢没有像你期望的那样工作,你在这里做的是检查属性值指定属性("data-params")的值等于"undefined",仅当属性为data-params="undefined"时,将返回true

if (object.getAttribute("data-params") === "undefined") { 
    // the "data-params" attribute-value is exactly "undefined" 
    // note that `getAttribute()` is a 
} 

你想要做什么,我怀疑是:

var typeOfObjectAttribute = typeof object.getAttribute("data-params"); 

if (typeOfObjectAttribute === null || typeOfObjectAttribute === "") { 
    // data-params attribute doesn't exist on that Node. 
} 

注意–根据Mozilla的开发者网络(在被Element.getAttribute()参考,下同)–指出:

getAttribute()返回元素上指定属性的值。如果给定的属性不存在,则返回的值将是null""(空字符串)…

值得注意的是,getAttribute()是Element节点的一种方法,而不是通用对象。

顺便说一下,你也可以用下面的办法(再次测试该属性是集):

// here we look to see if the 'params' key is present in the 
// HTMLElement.dataset object of the element, and then invert 
// that result using the '!' operator, to check that the 
// attribute *isn't* present: 
if (!('params' in document.getElementById('elementID').dataset)) { 
    // the data-params attribute is not present. 
} 

参考文献:

+0

它不起作用 – jollykoshy

0

您也可以使用数据集API。

HTMLElement.dataset

的HTMLElement.dataset只读属性允许访问,无论是在阅读和写作模式,(数据并行*)设置元素上的所有自定义数据属性。它是DOMString的映射,每个自定义数据属性都有一个条目。

不幸的是,这不会在IE10中工作,但我很确定在那里有一个垫片。

下面是一个例子

var containerData \t = document.querySelector('#container').dataset, 
 
    contentData \t = document.querySelector('#content').dataset; 
 

 
// Check if dataset is empty or not. 
 
console.log(Object.keys(containerData).length === 0); 
 
console.log(Object.keys(contentData).length === 0); 
 

 
// Check for specific data 
 
if (containerData.hasOwnProperty('bar')) { 
 
    console.log(containerData.bar); 
 
} 
 

 
// Here is the dataset 
 
console.log(containerData);
<div id="container" data-foo="bar" data-bar="foo"> 
 
    <div id="content"> 
 
    Content 
 
    </div> 
 
</div>

3

检查针对空也产生该溶液。

if (object.getAttribute("data-params") === null) { 
//data attribute doesn't exist 
}else{ 
//data attribute exists 
}