jQuery Hide/Show if conditional statement

后端 未结 2 1783
时光取名叫无心
时光取名叫无心 2021-01-07 19:15

I do this a lot:

var condition = true;
if (condition === true) {
    $(\'#condition_dependancy\').show();
} else {
    $(\'#condition_dependancy\').hide();
}         


        
2条回答
  •  走了就别回头了
    2021-01-07 19:24

    You can use toggle:

    var condition = true;
    $('#condition_dependancy').toggle(condition);
    

    Side note: Don't use things like

    if (condition === true)
    

    unless there's a possibility that condition will have a different "truthy"* value and you only want the expression to be true if it's precisely true and not if it's just truthy. In general == (boolean) and (in JavaScript) === (boolean) is just noise (although in JavaScript there are edge cases for using the === version).

    Prefer:

    if (condition)
    

    and (for the == false / === false case):

    if (!condition)
    

    * "truthy": In JavaScript, types can be coerced by expressions. Anywhere a boolean is expected, if you use something that isn't a boolean, it's coerced into being one. Things that coerce to true are called "truthy" values; things that coerce to false are called "falsey" values. The falsey values are 0, "", NaN, undefined, null, and of course, false. Everything else is truthy.

提交回复
热议问题