jQuery 如何编写jquery If else语句?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11495704/
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
How to write jquery If else statement?
提问by Alice
This code shows frm01:
此代码显示 frm01:
$(document).ready(function() {
$("#reg").click(function () {
$("#frm01").show("slide", { direction: "down" }, 1000);
});
});
But I want to hide frm01 if it is allready visible, and vice versa. How could I do this, please ?
但是如果 frm01 已经可见,我想隐藏它,反之亦然。请问我怎么能这样?
回答by Matt
Try jQuery's toggle()
method:
试试jQuery的toggle()
方法:
$(function() {
$("#reg").click(function () {
$("#frm01").toggle(1000);
});
});
You don't need jQuery to use if-else statements; Javascript implements those natively...
你不需要 jQuery 来使用 if-else 语句;Javascript 实现了那些本机...
$(function() {
$("#reg").click(function () {
if ($("#frm01").is(":visible"))
$("#frm01").slideUp(1000);
else
$("#frm01").slideDown(1000);
});
});
回答by undefined
try this:
尝试这个:
$(document).ready(function() {
$("#reg").click(function () {
if ($("#frm01").is(':hidden')) {
$("#frm01").show("slide", { direction: "down" }, 1000);
} else {
$("#frm01").hide(1000);
}
});
});
回答by Max Girkens
$("#reg").on('click', function () {
$("#frm01:hidden").show("slide", { direction: "down" }, 1000);
$("#frm01:visible").hide("slide", { direction: "up" }, 1000);
});
or
或者
$("#reg").toggle(
function () {
$("#frm01").show("slide", { direction: "down" }, 1000);
},
function(){
$("#frm01").hide("slide", { direction: "up" }, 1000);
}
);
should also work
也应该工作
回答by Fazle Elahee
You can use $.toggle() method to show and hide. Some time need to identify whether elements are hide or show.
您可以使用 $.toggle() 方法来显示和隐藏。有时需要确定元素是隐藏还是显示。
$("#reg").click(function () {
if($("#frm01").hasClass('fram1-slide-on')){
$("#frm01").hide();
$("#frm01").removeClass('fram1-slide-on');
} else {
$("#frm01").show("slide", { direction: "down" }, 1000);
$("#frm01").addClass('fram1-slide-on');
}
});
});