是否存在像 jQuery.toggle(boolean) 这样的东西?
我经常写类似下面的代码。它基本上根据某些条件切换元素。
在以下虚构示例中,条件为“如果选中agree
”复选框且name
字段不为空”。
$("button").click(function() {
if ($("#agree").is(":checked") && $("#name").val() != "" ) {
$("#mydiv").show();
} else {
$("#mydiv").hide();
}
});
我希望有某种 jQuery 函数可以像这样工作。
$("button").click(function() {
var condition = $("#agree").is(":checked") && $("#name").val() != "" );
$("#mydiv").toggle(condition);
});
那里有这样的东西吗?或者除了第一个示例之外还有其他方法可以以较少的 if-else-ish
方式执行此操作吗?
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 agree
checkbox is checked and the name
field isn't empty".
$("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.
$("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-ish
way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
好吧,所以我是个白痴,在提问之前需要 RTM。
jQuery.toggle() 允许您开箱即用地执行此操作。
Ok, so I am an idiot and need to RTM before I ask questions.
jQuery.toggle() allows you to do this out of the box.
首先,让我们看看我是否正确理解你想要做什么......
您想要查看复选框的状态(选中或未选中)并根据该值的状态隐藏或显示第二个 div。
定义此样式:
使用此 JavaScript:
可以在此处找到 jQuery 的文档:
http://api.jquery.com/toggleClass/
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.
Define this style:
Use this JavaScript:
The documentation from jQuery on it can be found here:
http://api.jquery.com/toggleClass/
您可以自己编写该函数。
然后像这样使用它:
You could write the function yourself.
Then use it like this:
语法4
$(selector).toggle(display)
显示
true - 显示元素。
false - 隐藏元素。
Syntax 4
$(selector).toggle(display)
display
true - to show the element.
false - to hide the element.
如果
toggle()
不适合你(例如因为它有动画),你可以编写一个小的 jQuery 插件,如下所示:然后像这样使用它:
If
toggle()
is not good for you (e.g. because it animates), you can write a small jQuery plugin, like this:and then use it like this: