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

纵饮孤独 提交于 2021-02-05 09:35:20

问题


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>");
        }
    })
})();

回答1:


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') {
   .....
}



回答2:


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.



来源:https://stackoverflow.com/questions/38649913/booleanfalse-returns-true-any-alternative

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!