2015-09-09 31 views
0

我想在加載所有特定圖像集時調用函數。目前,我僅僅使用.onload作爲最後一張圖片,它在99%的時間內都能正常工作,但有時會出現問題。什麼是最好的方式去做這件事?我意識到我可以爲每個圖像創建一個.onload,然後在所有其他圖像已經加載的情況下檢查函數內部,但我覺得必須有一個更有效的方法。如何在幾張圖像的最後一張圖像加載時調用某個功能?

這裏是我的代碼:

P1LCImage.src = "images/" + P1LC + "-card.png"; 
P1RCImage.src = "images/" + P1RC + "-card.png"; 
P2LCImage.src = "images/" + P2LC + "-card.png"; 
P2RCImage.src = "images/" + P2RC + "-card.png"; 
P3LCImage.src = "images/" + P3LC + "-card.png"; 
P3RCImage.src = "images/" + P3RC + "-card.png"; 
P4LCImage.src = "images/" + P4LC + "-card.png"; 
P4RCImage.src = "images/" + P4RC + "-card.png"; 
P5LCImage.src = "images/" + P5LC + "-card.png"; 
P5RCImage.src = "images/" + P5RC + "-card.png"; 
P6LCImage.src = "images/" + P6LC + "-card.png"; 
P6RCImage.src = "images/" + P6RC + "-card.png"; 
blankCardImage.src = "images/blank-card.png"; 
protectedCardImage.src = "images/protected-card.png"; 
voteCount1.src = "images/voteCount1.png"; 
voteCount2.src = "images/voteCount2.png"; 
voteCount3.src = "images/voteCount3.png"; 
voteCount4.src = "images/voteCount4.png"; 
voteCount5.src = "images/voteCount5.png"; 
voteCount6.src = "images/voteCount6.png"; 
voteCount6.onload = function() { 
    drawTable();   
    }; 
+2

您可以使用計數器計數加載的圖像,並且在加載所有圖像時調用回調。 – meskobalazs

回答

3

你可以一個onload添加到每個圖像,並讓他們每個增量的計數器。當計數器達到圖像的數量,所有圖像都加載,你叫drawTable()

示例代碼:

var numImgs = 6; 
var numLoaded = 0; 

function imgLoaded() { 

if(++numLoaded === numImgs) 
    drawTable();   
}; 

voteCount1.onload = imgLoaded; 
voteCount2.onload = imgLoaded; 
voteCount3.onload = imgLoaded; 
voteCount4.onload = imgLoaded; 
voteCount5.onload = imgLoaded; 
voteCount6.onload = imgLoaded; 
+0

謝謝,這很完美。 – Jonah

2

如果你知道你需要多少圖像顯示,你可以按照這個方法:

var counter = 0; 
var TOTAL_IMAGES = 20; 
function imageOnLoad() { 
    if (++counter >= TOTAL_IMAGES) { 
     drawTable(); 
    } 
} 

當然TOTAL_IMAGES可能是變量,在這種情況下,你可能會使用數組長度或類似的東西。我會將事件附加到DOM類上,因此您無需在每個圖像上指定onload事件。例如,讓我們假設圖片被封裝在一個ID爲gallery的div中。在這種情況下,您可以這樣做:

document.querySelectorAll('#gallery img').forEach(function() { 
    this.onclick = imageOnLoad; 
}); 
+0

我喜歡你的答案。它非常全面。 – JoSSte

相關問題