jQuery +如果语句
我正在尝试自学一些基本的 jquery,但在尝试使用 if 语句时遇到了问题。我的代码如下:
var animate = 0;
$('a').click(function () {
if (animate == 0) {
$('#shadow').fadeOut(500);
var animate = 1;
}
});
我希望进一步使用一些 else 语句,以便根据“animate”的值,单击时它将执行不同的 jquery 操作。我确信我忽略了一些明显的事情,但我正在用头撞墙试图弄清楚它是什么。
任何帮助将不胜感激!
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:
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.
Any help would be most appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您使用 var 声明变量时,它就成为局部变量,这意味着它在该范围内是新的。
实现您想要的目标的快速(但肮脏)方法如下:
请注意,这可能是一个相当不完美的解决方案;特别是
animate
不会将自身设置回 0(不过,您可以使用回调函数作为fadeOut
的第二个参数来执行此操作)。更好的解决方案可能是在您正在使用的特定项目上放置(和删除)一个类:
但是,我不知道您的实现的细节,所以我会让您弄清楚什么是适合您的特殊需求。
When you use
var
to declare a variable, then it becomes a local variable, which means it's new within that scope.The quick (and dirty) way for you to get the goal you want is something like:
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 tofadeOut
, though).A still better solution is probably to place (and remove) a class on the particular item you're working with:
However, I don't know the details of your implementation, so I'll let you figure out what is right for your particular needs.
将 1 分配给
animate
时,不应再次使用var
关键字。通过这样做,您将导致语法错误,因为animate
已在同一范围内声明。You shouldn't use the
var
keyword again when assigning 1 toanimate
. By doing this, you are causing a syntax error sinceanimate
has already been declared within the same scope.您正在通过在 click 函数中使用 var 重新定义 animate。
更改
为
This 将使您在外部范围中设置 animate 变量的值,而不是在单击函数内的范围内创建动画。
华泰
You're redefining animate by using var inside the click function.
change
to
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.
HTH