布尔数据 - *属性 [英] Boolean data-* Attributes
问题描述
您可以使用数据 - *
属性作为布尔属性吗?如果没有,是否有其他选择?
Can you use data-*
attributes as boolean attributes? If not, is there an alternative?
例如,您可以
<input disabled>
在某些情况下有用
<input data-on>
使用 data-on =true
或者 data-on =
是不可取的 - 属性的 presence 应该表明它的布尔值。
Using data-on="true"
or data-on=""
is not desirable -- the presence of the attribute should indicate its boolean value.
推荐答案
您确实可以使用数据 - *
属性,就好像一样布尔属性 - 但是,就数据集
而言,< input data-on>
相当于< input data-on =>
。这意味着,与 required
或其他布尔属性不同,您将无法执行此操作:
You can indeed use data-*
attributes as if they were boolean attributes - however, as far as dataset
is concerned <input data-on>
is equivalent of <input data-on="">
. This means that unlike required
or other boolean attributes you won't be able to do this:
<input class="some-class" data-on required>
var elementOfInterest = document.querySelector(".some-class");
if (elementOfInterest.dataset.on) {
// We will never get here because dataset.on === ""
// and "" == false
}
if (elementOfInterest.required) {
// We *do* get here because required is a boolean attribute
}
相反,您需要对undefined进行明确检查:
Instead you'll need to do an explicit check against undefined:
if (elementOfInterest.dataset.on !== undefined) {
// We will get here because "" !== undefined
}
这使您无法区分数据
和数据-on =
,但是如果你把它当作一个布尔属性,它们都会加起来相同的东西(只有缺少属性才能表示伪造。)
This gives you no way of distinguishing between data-on
and data-on=""
, but if you are treating it as a boolean attribute, they both add up to the same thing anyway (only the absence of the attribute indicates falsity.)
这篇关于布尔数据 - *属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!