考慮下面的代碼:的setTimeout在一個循環和傳遞變量使用後
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。 謝謝!
? –
@Diodeus:我猜測代碼執行時DOM元素不存在。因此,檢查元素的寬度必須被延遲。 – Amberlamps
這是真的!這正是問題 – Jonas