Reputation: 127
I am trying to load an set of images and apply different styles to each one as the load in. When I run my code I only get the last set of styles passed in to be applied to all images.
For a group of images ids $foo load that image into its own box and then apply a height.
for ( var i = 0; i < $foo.length; i = i + 1 ) {
$bar = i;
$('.box'+[i]).load('/getimage/'+$foo[i]', function(){style($(this), $bar);}
}
function style(img, $bar){
img.css('height', $bar);
}
Each image I format with the style function only gets set to height of last value of $bar.
I want to set the height to whatever the value of $bar is at the time that image is loaded.
Upvotes: 1
Views: 2400
Reputation: 68420
You could use a closure to get the correct value on each iteration
for ( var i = 0; i < $foo.length; i = i + 1 ) {
$bar = i;
// closure to get correct value for i
(function(index) {
$('.box'+[index]).load('/getimage/'+$foo[index], function() {
style($(this), index);
});
})(i);
}
function style(img, $bar){
img.css('height', $bar);
}
Upvotes: 4