set/getAttribute 比较只适用于字符串?

set/getAttribute comparisons only work with strings?

我想根据是否已访问将 span 节点的 visited 属性设置为 truefalse

test();

function test () {

    var el = document.createElement("span");
    el.setAttribute("visited", false);

    el.setAttribute("visited", true);

    alert(el.getAttribute("visited") === true); //False
    alert(el.getAttribute("visited") === "true"); //True

}

我最初将属性 "visited" 设置为布尔值 false,然后将布尔值设置为 true。我注意到当我检查属性是否为 true 时,它返回 false,但如果我检查字符串 true,它返回 true。

MSN Docs只说attributeName需要是string,不是value。那么为什么与布尔值比较不起作用?

FIDDLE

这是因为 getAttribute return 类型是 string 而不是 bool

Return 值:一个字符串,表示指定属性的值

Note: If the attribute does not exist, the return value is null or an empty string ("")

=== 运算符同时检查值和类型(没有类型的隐式强制转换)。

因为 getAttribute returns 是一个字符串值,所以比较只是 true 与字符串 "true" 相比,而不是 [=] 的布尔值比较13=].

换句话说,当使用 === 运算符时...

true === 'true' // false
'true' === 'true' // true
true === true // true

这是 HTML 标准定义的属性定义:

3.2.3.1 Attributes

Except where otherwise specified, attributes on HTML elements may have any string value, including the empty string. Except where explicitly stated, there is no restriction on what text can be specified in such attributes.

因此,重复已经说过的话,HTML 属性始终是字符串。