Rya*_*ies 3 jquery if-statement
我正在尝试自学一些基本的jquery,并且遇到了我正试图使用的if语句的问题.我的代码如下:
var animate = 0;
$('a').click(function () {
if (animate == 0) {
$('#shadow').fadeOut(500);
var animate = 1;
}
});
Run Code Online (Sandbox Code Playgroud)
我希望在这一行中使用其他一些语句,这样根据"animate"的值,它会在单击时执行不同的jquery操作.我敢肯定我忽略了一些显而易见的事情,但我正在撞墙试图找出它是什么.
非常感激任何的帮助!
当您使用var声明变量时,它将成为局部变量,这意味着它在该范围内是新的.
快速(和肮脏)的方式让你获得你想要的目标是这样的:
var animate = 0;
$('a').click(function() {
if (animate === 0) {
$('#shadow').fadeOut(500);
animate = 1; // note the lack of "var"
}
});
Run Code Online (Sandbox Code Playgroud)
请注意,这可能是一个非常不完美的解决方案; 特别animate是不会将自身设置为0(fadeOut尽管如此,您可以使用回调函数作为第二个参数).
更好的解决方案可能是在您正在使用的特定项目上放置(并删除)一个类:
$('a').click(function() {
if (!$('#shadow').hasClass('animating')) {
$('#shadow').addClass('animating').fadeOut(500, function() {
$(this).removeClass('animating');
});
}
});
Run Code Online (Sandbox Code Playgroud)
但是,我不知道您的实施细节,所以我会让您找出适合您特定需求的内容.