Javascript 像 jQuery.toggle(boolean) 这样的东西存在吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2388664/
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
Does something like jQuery.toggle(boolean) exist?
提问by jessegavin
I write something similar to the following code a lot. It basically toggles an element based on some condition.
我写了很多类似于以下代码的东西。它基本上根据某些条件切换元素。
In the following made-up example, the condition is "If the agreecheckbox is checked and the namefield isn't empty".
在下面的虚构示例中,条件是“如果agree复选框被选中并且该name字段不为空”。
$("button").click(function() {
if ($("#agree").is(":checked") && $("#name").val() != "" ) {
$("#mydiv").show();
} else {
$("#mydiv").hide();
}
});
I wish there was some sort of jQuery function that would work like this.
我希望有某种像这样工作的 jQuery 函数。
$("button").click(function() {
var condition = $("#agree").is(":checked") && $("#name").val() != "" );
$("#mydiv").toggle(condition);
});
Is there something like this out there? Or are there other ways besides the first example to do this in a less if-else-ishway?
有这样的东西吗?或者除了第一个例子之外还有其他方法可以以较少的if-else-ish方式做到这一点吗?
回答by jessegavin
Ok, so I am an idiot and need to RTM before I ask questions.
好的,所以我是个白痴,在提问之前需要 RTM。
jQuery.toggle()allows you to do this out of the box.
jQuery.toggle()允许您开箱即用。
$("button").click(function() {
var condition = $("#agree").is(":checked") && $("#name").val() != "" );
$("#mydiv").toggle(condition);
});
回答by Richard June
First, lets see if I understand what you want to do correctly... You want to look at the state of a checkbox(checked or not) and hide or show a second div based on the status of that value.
首先,让我们看看我是否理解您想要正确执行的操作...您想查看复选框的状态(选中或未选中)并根据该值的状态隐藏或显示第二个 div。
Define this style:
定义这种风格:
.noDisplay {
display:none;
}
Use this JavaScript:
使用这个 JavaScript:
$("button").click(function() {
$("#mydiv").toggleClass("noDisplay", $("#name").val() == "");
});
The documentation from jQuery on it can be found here: http://api.jquery.com/toggleClass/
jQuery 上的文档可以在这里找到:http: //api.jquery.com/toggleClass/
回答by John Fisher
You could write the function yourself.
你可以自己写函数。
function toggleIf(element, condition) {
if (condition) { element.show(); }
else { element.hide(); }
}
Then use it like this:
然后像这样使用它:
toggleIf($("button"), $("#agree").is(":checked") && $("#name").val() != "");
回答by Yossi Shasho
If toggle()is not good for you (e.g. because it animates), you can write a small jQuery plugin, like this:
如果toggle()不适合你(例如因为它有动画效果),你可以写一个小的 jQuery 插件,像这样:
$.fn.toggleIf = function(showOrHide) {
return this.each(function() {
if (showOrHide) {
return $(this).show();
} else {
return $(this).hide();
}
});
};
and then use it like this:
然后像这样使用它:
$(element).toggleIf(condition);

