检查没有值的HTML5数据属性 [英] Checking for HTML5 data attribute with no value

查看:147
本文介绍了检查没有值的HTML5数据属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个元素,其HTML5 数据属性没有任何值,只是像这样的键:

 < div id =1data-foo> Foo< / div> 

如果我使用 dataset ,像这样:

  getElementById(1)。dataset.foo 

然后,这将返回一个空值,并且我无法区分该元素是否具有 data-foo 属性。是否有方法检查元素是否具有 data-foo 属性,而不管它是否具有指定的值?

hasAttribute 方法检查元素是否包含属性来完成此操作:

  document.getElementById('1')。hasAttribute('data-foo')


I have an element that has an HTML5 data attribute with no value but just the key like this:

<div id="1" data-foo>Foo</div>

If I use dataset like this:

getElementById("1").dataset.foo

then, this will return a null value, and I cannot distinguish whether the element has data-foo attribute or not. Is there are way to check if the element has a data-foo attribute regardless of whether it has a specified value?

解决方案

You can accomplish this by checking if the element contains the attribute using the hasAttribute method:

document.getElementById('1').hasAttribute('data-foo')

这篇关于检查没有值的HTML5数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆