考虑 HTML 文件中的示例代码:
<div id="book"
data-id="47909"
data-title="Under The Dome"
data-author="Stephen King"
data-year="2009">
</div>
选择 book 元素:
book = document.querySelector("#book");
每当我将某些属性设置为 null
或 undefined
时,它会分别将其设置为字符串“null”、“undefined”:
book.dataset.author = null
typeof book.dataset.author
"string"
book.dataset.year = undefined
typeof book.dataset.year
"string"
同时
let a = null;
typeof a
"object"
let b = undefined;
typeof b
"undefined"
有人可以解释一下为什么它会这样吗?这是否与以下事实有关:由于它是元素属性的性质,最终所有内容都将转换为字符串?
谢谢!
最佳答案
On getting, the dataset IDL attribute must return a DOMStringMap whose associated element is this element.
Attributes have a namespace (null or a non-empty string), namespace prefix (null or a non-empty string), local name (a non-empty string), value (a string), and element (null or an element).
因此该值在返回之前被转换为字符串
String(null); //"null"
String(undefined); //"undefined"
String(1); //"1"
关于javascript - HTML5 数据属性将 null 和 undefined 转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48539552/