jQuery 隐藏/显示 if 条件语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20541618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery Hide/Show if conditional statement
提问by Dom Vinyard
I do this a lot:
我经常这样做:
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.
但我只是想知道是否有内置的东西。
回答by T.J. Crowder
You can use toggle
:
您可以使用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).
除非有可能condition
具有不同的“truthy”* 值,并且您只希望表达式为真,如果它是准确的,true
而不是它只是真的。一般来说,== (boolean)
和(在 JavaScript 中)=== (boolean)
只是噪音(尽管在 JavaScript 中存在使用===
版本的边缘情况)。
Prefer:
更喜欢:
if (condition)
and (for the == false
/ === false
case):
和(对于== false
/=== false
情况):
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.
* "truthy": 在 JavaScript 中,类型可以被表达式强制转换。在任何需要布尔值的地方,如果您使用不是布尔值的东西,它就会被强制为一个。强迫的东西true
被称为“真实”值;强迫的东西false
被称为“虚假”值。falsey 值是0
、""
、NaN
、undefined
、null
,当然还有false
。其他一切都是真实的。
回答by A. Wolff
Using toggle()
:
使用toggle()
:
$('#condition_dependancy').toggle(condition);