次のコードを検討してください。
function func() {
var totalWidths = 0;
for( var i = 0, count = arr.length; i < count; i++ ) {
var image = arr[i];
insertElemInDOM(image);
preloadImage(image,function(){
var w = image.width();
totalWidths += w;
});
}
// do something with the variable "totalWidths"
doSomething(totalWidths)
}
ここに2つの問題があります。画像は常に同じになり(最初の問題)、無名関数で解決できます。
for(...) {
(function(image) {
preload(image,function() {
// now image is the correct one
});
})(image);
}
しかし、後でdoSomething(totalWidths)で使用するために、totalWidths変数を管理するにはどうすればよいですか?前のコードは、totalWidthsの値が0になります。ありがとう!