jQuery + If 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6037769/
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 + If Statement
提问by Ryan Gillies
I'm trying to teach myself some basic jquery and am having trouble with an if statement I'm trying to use. My code is as follows:
我正在尝试自学一些基本的 jquery,但在尝试使用 if 语句时遇到了问题。我的代码如下:
var animate = 0;
$('a').click(function () {
if (animate == 0) {
$('#shadow').fadeOut(500);
var animate = 1;
}
});
I'm hoping to use some else statements further down the line, so that depending on the value of "animate" it will perform a different jquery action when clicked. I'm sure I've overlooked something obvious, but I'm banging my head against a wall trying to figure out what it is.
我希望在后面使用一些 else 语句,以便根据“animate”的值在单击时执行不同的 jquery 操作。我确定我忽略了一些明显的东西,但我正在用头撞墙试图弄清楚它是什么。
Any help would be most appreciated!
非常感激任何的帮助!
回答by Luke Sneeringer
When you use var
to declare a variable, then it becomes a local variable, which means it's new within that scope.
当你var
用来声明一个变量时,它就变成了一个局部变量,这意味着它在那个范围内是新的。
The quick (and dirty) way for you to get the goal you want is something like:
您获得所需目标的快速(和肮脏)方式如下:
var animate = 0;
$('a').click(function() {
if (animate === 0) {
$('#shadow').fadeOut(500);
animate = 1; // note the lack of "var"
}
});
Note that this is probably a pretty imperfect solution; in particular animate
doesn't set itself back to 0 (you can do this with a callback function as the second argument to fadeOut
, though).
请注意,这可能是一个非常不完美的解决方案;特别animate
是不会将自身设置回 0(不过,您可以使用回调函数作为 的第二个参数来执行此操作fadeOut
)。
A still better solution is probably to place (and remove) a class on the particular item you're working with:
更好的解决方案可能是在您正在使用的特定项目上放置(并删除)一个类:
$('a').click(function() {
if (!$('#shadow').hasClass('animating')) {
$('#shadow').addClass('animating').fadeOut(500, function() {
$(this).removeClass('animating');
});
}
});
However, I don't know the details of your implementation, so I'll let you figure out what is right for your particular needs.
但是,我不知道您实现的详细信息,因此我会让您弄清楚什么适合您的特定需求。
回答by Ryan Berger
You shouldn't use the var
keyword again when assigning 1 to animate
. By doing this, you are causing a syntax error since animate
has already been declared within the same scope.
var
将 1 分配给 时,不应再次使用该关键字animate
。这样做会导致语法错误,因为animate
已经在同一范围内声明。
回答by RedWolves
You're redefining animate by using var inside the click function.
您正在通过在 click 函数中使用 var 来重新定义动画。
change
改变
var animate = 1;
to
到
animate = 1;
This will make it so you set the value of the animate variable in the outer scope and not animate that you are creating in scope within the click function.
这将使您在外部作用域中设置 animate 变量的值,而不是在单击函数内的作用域内设置动画。
HTH
HTH