jQuery syntax error? Css and Animate in 'if' and 'else' statements
Edit - Ive changed my code:
This works fine:
$(".image-div").click(function () {
if ($(this).css('z-index') == 1)
$(this).css('z-index','2');
else
$(this).css('z-index','1');
});
And this also works:
$(".image-div").click(function () {
if ($(this).css('z-index') == 1)
$(this).animate({
width: '500px'
}, 5000, function() {
// Animation complete.
});
else
$(this).animate({
width: '250px'
}, 5000, function() {
/开发者_StackOverflow社区/ Animation complete.
});
});
But this doesn't do anything:
$(".image-div").click(function () {
if ($(this).css('z-index') == 1)
$(this).css('z-index','2');
$(this).animate({
width: '500px'
}, 5000, function() {
// Animation complete.
});
else
$(this).css('z-index','1');
$(this).animate({
width: '250px'
}, 5000, function() {
// Animation complete.
});
});
Thanks
Yes. No beginning {
or ending }
after the if & before the else.
Also, it looks like a double });
at the bottom.
Looks like you need curly braces around your if...otherwise, that else is floating with no connected if.
[ADDED] Okay, curly braces are needed for ANY controls with multiple statements following. The following works fine without curly braces because there's only one statement after each control:
if( condition ) doSomething();
else doSomethingElse();
However, this will break:
if( condition )
doSomething();
doAnotherThing();
else
doSomethingElse();
Why? Because the IF in this case only covers this:
if( condition )
doSomething();
Then, you have this sitting out in the middle of nowhere:
doAnotherThing();
else
doSoemthingElse();
doAnotherThing is NOT contained inside the if(), and thereby neither is your else{}. So, your else loses its attachment to the if and the code breaks. It is, IMHO, best practice to ALWAYS use curly braces, because if you don't, you or someone else may come in and add the doAnotherThing() line to the code thinking it's contained in the if() and inadvertently break the code.
That said, your if/else both contain multiple statements. So, from strictly a syntax point, your code needs to be:
$(".image-div").click(function () {
if ($(this).css('z-index') == 1) {
$(this).css('z-index','2');
$(this).animate({
width: '500px'
}, 5000, function() {
// Animation complete.
});
}
else {
var divRef = this;
$(this).animate({
width: '250px'
}, 5000, function() {
$(divRef).css('z-index','1');
});
}
});
精彩评论