简体   繁体   English

Boolean(“ false”)返回true。还有其他选择吗?

[英]Boolean(“false”) returns true.. any alternative?

I am using jquery to write true and false strings to data- html attributes. 我正在使用jquery将true和false字符串写入datahtml属性。 However when I write false to one of the attributes, and then check it it false, it returns true. 但是,当我向其中一个属性写入false,然后将其检查为false时,它将返回true。 I also read online that it supposed to do that, which really makes no sense at all. 我还在线阅读了它应该这样做的信息,这根本没有任何意义。

Does anyone have an alternative? 有人有其他选择吗? Any help would be really appreciated! 任何帮助将非常感激!

(function() {
    // $(".opt-header").click(function () {
    $(document).on("click", ".opt-header", function() {
        console.log($(this).attr("data-is-panel-activated"));
        var is_activate = Boolean($(this).attr("data-is-panel-activated"));
        $(this).siblings(":not(.opt-group-toggle)").slideToggle(300);
        console.log(is_activate);
        if (is_activate) {
            $(this).find(".fa-angle-right").replaceWith("<i class='fa fa-angle-down'></i>");
            $(this).attr("data-is-panel-activated", "false");
        } else {
            $(this).attr("data-is-panel-activated", "true");
            $(this).find(".fa-angle-down").replaceWith("<i class='fa fa-angle-right'></i>");
        }
    })
})();

Boolean('false') will return true because the string 'false' is truthy. Boolean('false')将返回true因为字符串'false'是真实的。

You could just run a check to see if the string equals 'false': 您可以运行检查以查看字符串是否等于“ false”:

if ($(this).attr("data-is-panel-activated") === 'false') {
   .....
}

The simplest fix would be: 最简单的解决方法是:

var is_activate = $(this).attr("data-is-panel-activated") !== "false";

or 要么

var is_activate = $(this).attr("data-is-panel-activated") === "true";

depending on which semantics makes more sense for your code. 取决于哪种语义对您的代码更有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM