jQuery隐藏/显示条件语句 [英] jQuery Hide/Show if conditional statement

查看:61
本文介绍了jQuery隐藏/显示条件语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了很多:

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

这可以是语法清洁吗?我可以写自己的:

Can this be any cleaner syntactically? I could write my own:

$('#condition_dependancy').hidden(condition);

但我只是想知道是否有任何内置的东西。

But i'm just wondering if there is anything built in.

推荐答案

您可以使用 切换

You can use toggle:

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






附注:请勿使用


Side note: Don't use things like

if (condition === true)

除非条件有可能具有不同的truthy*值,并且您只希望表达式为真,如果它是精确的 true 而不是它只是真的。通常 ==(布尔值)和(在JavaScript中) ===(布尔值)只是噪音(尽管在JavaScript有使用 === 版本的边缘情况。

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).

首选:

if (condition)

和(对于 == false / === false 案例):

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

if (!condition)






*truthy:在JavaScript中,类型可以通过表达式强制执行。在任何地方都需要布尔值,如果你使用不是布尔值的东西,它就会被强制成为布尔值。强加给 true 的东西被称为真实值;强制转换为 false 的内容称为falsey值。假名值为 0 NaN undefined null ,当然还有 false 。其他一切都很简洁。


* "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.

这篇关于jQuery隐藏/显示条件语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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