我想檢查一個HTML5數據屬性是否存在使用普通的JavaScript。 我試過下面的代碼片段,但它不起作用。如何檢查數據屬性是否存在與純JavaScript?
if(object.getAttribute("data-params")==="undefined") {
//data-attribute doesn't exist
}
我想檢查一個HTML5數據屬性是否存在使用普通的JavaScript。 我試過下面的代碼片段,但它不起作用。如何檢查數據屬性是否存在與純JavaScript?
if(object.getAttribute("data-params")==="undefined") {
//data-attribute doesn't exist
}
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
}
爲什麼作爲選擇的答案有這個被打上了嗎? – Doidgey
嘗試使用typeof:
if(typeof object.getAttribute("data-params") === "undefined") {
console.log('data-attribute doesn't exist');
}
你蒼做到這falsy值檢查
if(!object.getAttribute("data-params")) {
//data-attribute doesn't exist
}
原因getAttribute
可以返回null或空字符串
也可以使用object.hasAttribute("data-params")
只檢查屬性是否存在
您發佈的代碼不贏沒有像你期望的那樣工作,你在這裏做的是檢查屬性值指定屬性("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.
}
參考文獻:
它不起作用 – jollykoshy
您也可以使用數據集API。
的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>
檢查針對空也產生該溶液。
if (object.getAttribute("data-params") === null) {
//data attribute doesn't exist
}else{
//data attribute exists
}
'如果(typeof運算的obj [ 「數據屬性」] == 「未定義」){//此處代碼}' –