Javascript 使用布尔值隐藏/显示元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27950151/
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
Hide/show element with a boolean
提问by Aakil Fernandes
I tend to have a lot of these in my code
我的代码中往往有很多这些
if(shouldElementBeVisible)
$element.show()
else
$element.hide()
Is there any more elegant way packaged with javascript, jquery, or underscore? Ideally I want something that looks like this
有没有更优雅的方式与 javascript、jquery 或下划线打包在一起?理想情况下,我想要看起来像这样的东西
$element.showOrHideDependingOn(shouldElementBeVisible)
回答by Aakil Fernandes
Apparently you can just pass a boolean to the togglefunction
显然你可以只将一个布尔值传递给toggle函数
$element.toggle(shouldElementBeVisible)
回答by Zach Spencer
Yes there is!
就在这里!
$element.toggle();
Without any parameters, togglejust toggles the elements visibility (I don't mean the visibilityproperty) and depends on the current state of the element.
没有任何参数,toggle只需切换元素可见性(我不是指visibility属性)并取决于元素的当前状态。
$element.toggle(display);
If you call togglewith a boolean parameter, element is shown if it is trueand hiddenif it is false
如果您toggle使用布尔参数调用,则显示元素,如果是true,hidden如果是false
回答by Mike
jQuery has toggle: http://api.jquery.com/toggle/
jQuery 有toggle:http: //api.jquery.com/toggle/
$element.toggle();
$element.toggle();
This will show the element if it's hidden, and hide it if it's shown.
如果元素被隐藏,这将显示该元素,如果它被显示,则隐藏它。
回答by Mel
The function .toggle()changes the displayof the element.
该函数.toggle()更改display元素的 。
If you want to change visibility, instead, I'd suggest using the ?:operator. For this, on your CSS, set the visibility to the original state, and in the JS simply put:
如果您想更改visibility,我建议您使用?:运算符。为此,在您的 CSS 上,将可见性设置为原始状态,并在 JS 中简单地输入:
var checkboxChecked = $("#yourCheckbox").(":checked");
$("#yourElement").css("visibility", checkboxChecked ? "visible" : "hidden");

