问题
I\'d like to write a simple jQuery plugin that displays inline modals under specified elements. My idea is for the script to auto-init based on data attributes specified on elements.
A very basic example:
<p data-modal-target>Hover over me for an inline modal!</p>
<div data-modal-content data-modal-align=\"right\" data-modal-trigger=\"hover\" data-modal-offset=\"10px\"><!-- any desired syntax can go here --></div>
I\'m just wondering if data-modal-target
in the above example is valid, or does it have to be data-modal-target=\"true\"
? I don\'t care about anything crappier than IE9 etc, my only requirement is that it be valid HTML5.
回答1:
Yes, perfectly valid. In your case, data-modal-target
would represent a boolean attribute:
2.4.2 Boolean attributes
The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.
回答2:
Custom data attributes specification doesn't mention any changes to empty attributes handling, so general rules about empty attributes apply here:
Certain attributes may be specified by providing just the attribute name, with no value.
In the following example, the
disabled
attribute is given with the empty attribute syntax:<input disabled>
Note that empty attribute syntax is exactly equivalent to specifying the empty string as the value for the attribute, as in the following example.
<input disabled="">
So you are allowed to use empty custom data attributes, but special handling needed to use them as boolean.
If you are accessing attribute through element.dataset
:
- When an empty attribute is present, it's value is
""
. - When an attribute is absent, you are getting
undefined
.
Therefore, you can't just check as if (element.dataset.myattr)
because it will always be false
.
You can and should check boolean attributes as if (element.dataset.myattr !== undefined)
.
Lloyd's answer is incorrect. He mentions link to boolean attributes microsyntax, but data-*
attributes are not specified as boolean in spec.
回答3:
Yes, it is valid syntax to omit value for a custom data attribute.
"Attributes can be specified in four different ways:
Empty attribute syntax Just the attribute name. The value is implicitly the empty string. [...]" https://developers.whatwg.org/syntax.html#attributes-0
回答4:
On one hand, it passes the validator 16.5.7 https://validator.w3.org/nu/#textarea :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>a</title>
</head>
<body data-asdf>
</body>
</html>
On the other, HTML5 does not say in the specification of data-
attributes that they are boolean: https://www.w3.org/TR/html5/dom.html#custom-data-attribute while it says that very clearly for other boolean attributes like checked
https://www.w3.org/TR/html5/forms.html#attr-input-checked
来源:https://stackoverflow.com/questions/9729080/are-empty-html5-data-attributes-valid