我正在尝试加载一组图像并在加载时对每个图像应用不同的样式。当我运行我的代码时,我只获得传入的最后一组样式以应用于所有图像。
对于一组图像 ids $foo 将该图像加载到它自己的框中,然后应用高度。
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);
}
我使用 style 函数设置格式的每个图像仅设置为 $bar 的最后一个值的高度。
我想将高度设置为加载图像时 $bar 的值。
最佳答案
您可以使用闭包在每次迭代中获取正确的值
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);
}
关于javascript - 在循环中将参数传递给 jquery .load 回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22697400/