简体   繁体   中英

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

I am using jquery to write true and false strings to data- html attributes. However when I write false to one of the attributes, and then check it it false, it returns 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.

You could just run a check to see if the string equals '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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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