2011-02-09 16 views
1

從跟隨上: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。

回答

4

您有一個單一的i變量,它在所有回調中共享。

由於回調異步執行,它們將在循環結束後執行,當ilength時。

您需要將循環體放入一個單獨的函數,該函數以i作爲參數。
這樣,每個load回調將使用單獨的i變量(函數參數),它將永遠不會改變。

3

可以使用$.each()循環創建關閉(入索引爲它自己變量,而不是共享的),你需要......與.position()調用需要有點變化的,以及,你應該使用.css()這裏需要一個對象,像這樣:

function initResources() { 
    var newImage; 
    $.each(resourceData, function(i, data) { 
     newImage = $('<img alt="Big" id="imgA' + i + '" class="mediaImg" width="' + Math.round(data[2] * currentScale) + '" height="' + Math.round(data[3] * currentScale) + '" />'); 
     newImage.load(function() { 
      $(this).css({ top: Math.round(data[5] * currentScale), 
         left: Math.round(data[4] * currentScale) }); 
     }); 
     newImage[0].src = uploadFolder + '/' + imgData[data[1]][1]; 
     $('#thePage').append(newImage); 
    }); 
} 

你可以縮短這個了,但它不會更有效率。在.load()事件處理程序中保存我的內容,您可以參考this處理程序的元素,無需再次選擇它。

+0

如果您向`$ .each()`回調函數中添加了一個參數,您可以獲取`resourceData [i]`的值,而不必每次都查看數組。 – gnarf 2011-02-09 13:10:06