set/getAttribute比较仅适用于字符串? [英] set/getAttribute comparisons only work with strings?

查看:80
本文介绍了set/getAttribute比较仅适用于字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据是否具有 span 节点的 visited 属性设置为 true false 被访问过.

I would like to set a span node's visited attribute to true or false based on if it has been visited.

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.

I initially set the attribute "visited" to boolean false, then set the boolean to true. I noticed that when I checked if the attribute was true, it returned false, but if I checked the string true, it returned true.

MSN文档仅谈论attributeName因为需要是字符串,而不是值.那为什么不和bool进行比较呢?

The MSN Docs only talk about the attributeName as needing to be string, not the value. So why doesn't comparing against bools work?

FIDDLE

推荐答案

这是因为 getAttribute 返回类型是字符串而不是布尔值

This is because getAttribute return type is string not bool

返回值:一个字符串,代表指定属性的值.

注意:如果属性不存在,则返回值为null或返回空字符串(")

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

这篇关于set/getAttribute比较仅适用于字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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