從跟隨上:Jquery的具有麻煩的定位圖像
Javascript wait for image to load before calling Ajax
function initResources() {
var newImage;
for (i = 0; i < resourceData.length; i++) {
// Create the image
newImage = $('<img alt="Big" id="imgA' + i + '" class="mediaImg" width="' + Math.round(resourceData[i][2] * currentScale) + '" height="' + Math.round(resourceData[i][3] * currentScale) + '" />');
newImage.load(function() {
alert(i);
// Position
$('#imgA' + i).position().top(Math.round(resourceData[i][5] * currentScale));
$('#imgA' + i).position().left(Math.round(resourceData[i][4] * currentScale));
});
newImage[0].src = uploadFolder + '/' + imgData[resourceData[i][1]][1];
$('#thePage').append(newImage);
}
}
我有圖像的陣列。當頁面最初從服務器加載時,該函數遍歷所有圖像並將它們放在頁面上。
當頁面的比例發生變化時,也會調用此函數。縮放功能清除HTML並使用縮放倍數重新繪製所有內容。
這個函數的問題是,它總是提示resourceData.length,這是循環的結尾。我需要以某種方式將數據傳遞給加載函數,以便在圖像最終加載時引用正確的ID/i。
如果您向`$ .each()`回調函數中添加了一個參數,您可以獲取`resourceData [i]`的值,而不必每次都查看數組。 – gnarf 2011-02-09 13:10:06