Reputation: 5818
I have the following jQuery code:
$content.each(function(i) {
$body = $(this);
$(this).find('div.field-content')
.animate(
{
'top': 0
},
{
duration: 500,
complete: function () {
$(this).css('top', 0);
setBodyGradient($body);
}
}
);
});
In my case $content
has 5 items. The problem seems to be that on the last iteration, the animation complete call back for $content.eq(0)
has yet to fire, and when it does, the most recent version of $body
is sent to setBodyGradient
5 times, rather than the version of $body
at the point the callback was created.
I should say I'm running JQuery 1.4.4 on Drupal, so perhaps this is a bug fixed in the latest JQuery or is it a feature?
I know I can get around it by using $content.eq(i)
instead, however I'm curious to know whether this is by design or buggy behaviour, and what the recommended method is? Should I always be looking to use $content.eq(i)
?
Upvotes: 2
Views: 116
Reputation: 8845
Do this instead:
$content.each(function(i) {
var $body = $(this);
Otherwise $body
will be a global variable and will resolve to the list item currently being processed. When the loop ends it will resolve to the last list item.
Since the callbacks are executed after the loop is done $body
will always resolve to the last element in the list.
Using var
makes $body
a part of the scope chain of the function used by .each()
. This means that $body
will always resolve to the 'correct' list item.
To see the difference, remove the var
keyword immediately in front of $body
from this fiddle and check your console.
Upvotes: 3