简体   繁体   中英

Passing parameters to jquery .load callback function in a loop

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM