[英]Checking for HTML5 data attribute with no value
I have an element that has an HTML5 data
attribute with no value but just the key like this: 我有一个元素具有HTML5 data
属性没有值,但只有这样的键:
<div id="1" data-foo>Foo</div>
If I use dataset
like this: 如果我使用这样的dataset
:
getElementById("1").dataset.foo
then, this will return a null value, and I cannot distinguish whether the element has data-foo
attribute or not. 那么,这将返回一个空值,我无法区分该元素是否具有data-foo
属性。 Is there are way to check if the element has a data-foo
attribute regardless of whether it has a specified value? 是否有办法检查元素是否具有data-foo
属性,无论它是否具有指定值?
您可以通过使用hasAttribute
方法检查元素是否包含该属性来完成此操作:
document.getElementById('1').hasAttribute('data-foo')
If the element does not feature the data-foo
attribute, a call to dataset.foo
will return undefined
, rather than null
(or an empty string in the case of an empty attribute). 如果元素不具有data-foo
属性,则对dataset.foo
的调用将返回undefined
,而不是null
(或者在空属性的情况下为空字符串)。
You should check the actual value, as follows: 您应该检查实际值,如下所示:
var fooVal = document.getElementById('div1').dataset.foo;
// data-foo is not present at all:
if( fooVal === undefined )
{
}
// data-foo is present but empty
if( fooVal === '' )
{
}
Of course, you could cast the logic to a simple boolean: 当然,您可以将逻辑转换为一个简单的布尔值:
var hasFoo = ( document.getElementById('div1').dataset.foo !== undefined );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.