Javascript 有没有办法检查数据属性是否存在?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12161132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:16:18  来源:igfitidea点击:

Is there a way that I can check if a data attribute exists?

javascriptjquery

提问by Angela

Is there some way that I can run the following:

有什么方法可以运行以下命令:

var data = $("#dataTable").data('timer');
var diffs = [];

for(var i = 0; i + 1 < data.length; i++) {
    diffs[i] = data[i + 1] - data[i];
}

alert(diffs.join(', '));

Onlyif there is an attribute called data-timer on the element with an id of #dataTable?

当 id 为 #dataTable 的元素上有一个名为 data-timer 的属性时?

回答by niiru

if ($("#dataTable").data('timer')) {
  ...
}

NOTE this only returns trueif the data attribute is not empty string or a "falsey" value e.g. 0or false.

注意这仅true在数据属性不是空字符串或“falsey”值(例如0or )时返回false

If you want to check for the existence of the data attribute, even if empty, do this:

如果要检查数据属性是否存在,即使为空,也可以这样做:

if (typeof $("#dataTable").data('timer') !== 'undefined') {
  ...
}

回答by Paul Fleming

if (typeof $("#dataTable").data('timer') !== 'undefined')
{
    // your code here
}

回答by sadmicrowave

In the interest of providing a different answer from the ones above; you could check it with Object.hasOwnProperty(...)like this:

为了提供与上述不同的答案;你可以Object.hasOwnProperty(...)像这样检查它:

 if( $("#dataTable").data().hasOwnProperty("timer") ){
     // the data-time property exists, now do you business! .....
 }

alternatively, if you have multiple data elements you want to iterate over you can variablize the .data()object and iterate over it like this:

或者,如果您有多个要迭代的数据元素,则可以.data()像这样对对象进行变量化并对其进行迭代:

 var objData = $("#dataTable").data();
 for ( data in objData ){
      if( data == 'timer' ){
            //...do the do
      }
 }

Not saying this solution is better than any of the other ones in here, but at least it's another approach...

并不是说这个解决方案比这里的任何其他解决方案都好,但至少它是另一种方法......

回答by Max

Or combine with some vanilla JS

或者结合一些香草JS

if ($("#dataTable").get(0).hasAttribute("data-timer")) {
  ...
}

回答by BZink

You can use jQuery's hasData method.

您可以使用 jQuery 的 hasData 方法。

http://api.jquery.com/jQuery.hasData/

http://api.jquery.com/jQuery.hasData/

The primary advantage of jQuery.hasData(element) is that it does not create and associate a data object with the element if none currently exists. In contrast, jQuery.data(element) always returns a data object to the caller, creating one if no data object previously existed.

jQuery.hasData(element) 的主要优点是它不会创建数据对象并将其与当前不存在的元素相关联。相比之下,jQuery.data(element) 总是向调用者返回一个数据对象,如果之前不存在数据对象,则创建一个。

This will only check for the existence of any data objects (or events) on your element, it won't be able to confirm if it specifically has a "timer" object.

这只会检查元素上是否存在任何数据对象(或事件),它无法确认它是否特别具有“计时器”对象。

回答by Ryan

If you want to distinguish between empty values and missing values you can use jQuery to check like this.

如果要区分空值和缺失值,可以使用 jQuery 进行检查。

<div id="element" data-foo="bar" data-empty=""></div>

<script>
"foo" in $('#element').data(); // true
"empty" in $('#element').data(); // true
"other" in $('#element').data(); // false
</script>

So from the original question you'd do this.

所以从最初的问题你会这样做。

if("timer" in $("#dataTable").data()) {
  // code
}

回答by Alex

You can create an extremely simple jQuery-plugin to query an element for this:

您可以创建一个非常简单的 jQuery 插件来为此查询元素:

$.fn.hasData = function(key) {
  return (typeof $(this).data(key) != 'undefined');
};

Then you can simply use $("#dataTable").hasData('timer')

然后你可以简单地使用 $("#dataTable").hasData('timer')

Gotchas:

陷阱:

  • Will return falseonly if the value does not exist (is undefined); if it's set to false/nullit hasData()will still return true.
  • It's different from the built-in $.hasData()which only checks if anydata on the element is set.
  • false仅当值不存在(是undefined)时才返回;如果它设置为false/nullhasData()仍然会返回true
  • 它与$.hasData()仅检查元素上是否设置了任何数据的内置函数不同。

回答by JerSchneid

I've found this works better with dynamically set data elements:

我发现这对于动态设置的数据元素效果更好:

if ($("#myelement").data('myfield')) {
  ...
}

回答by Rounin

All the answers here use the jQuery library.

这里的所有答案都使用 jQuery 库。

But the vanilla javascript is very straightforward.

但是香草 javascript 非常简单。

If you want to run a script only if the element with an idof #dataTablealsohas a data-timerattribute, then the steps are as follows:

如果你想只在带有idof的元素#dataTabledata-timer属性的情况下运行脚本,那么步骤如下:

// Locate the element

const myElement = document.getElementById('dataTable');

// Run conditional code

if (myElement.dataset.hasOwnProperty('timer')) {

  [... CODE HERE...]

}

回答by Animesh Singh

This is the easiest solution in my opinion is to select all the element which has certain data attribute:

在我看来,这是最简单的解决方案是选择所有具有特定数据属性的元素:

var data = $("#dataTable[data-timer]");
var diffs = [];

for(var i = 0; i + 1 < data.length; i++) {
    diffs[i] = data[i + 1] - data[i];
}

alert(diffs.join(', '));

Here is the screenshot of how it works.

这是它如何工作的屏幕截图。

console log of the jquery selector

jquery 选择器的控制台日志