I've a series of folders containing images numbered sequentially (1.jpg, 2.jpg, 3.jpg… etc). I'm trying to load the images with a for loop until the first non existing image is found. I read some other article managing similar problem (check if an image exists) with onload and onerror callback functions, but I'm stuck. Here there is some code I wrote to store the images in an array and display them in the HTML page along with their src:
var arrImages = new Array();
function loadImgSeq() {
for (var i = 0; i < 11; i++) {
arrImages[i] = new Image();
arrImages[i].src = "slides/" + i + ".jpg"
arrImages[i].width = 400;
document.body.appendChild(arrImages[i]);
document.write("<p>"+arrImages[i].src+"</p>");
}
}
PS:I've no experience in computer programming, I just do it as hobbyist.
Here is a way
var i=0,img;
function loadImgSeq() {
i++;
var img = new Image();
img.onload=function() {
document.body.appendChild(img);
loadImgSeg(); // if success, do it again - will not be called if error
}
img.src = "slides/" + i + ".jpg";// IMPORTANT, must be AFTER onload/onerror handler
}
UPDATE: If you get IE issues from cache, try
img.onload=img.complete=function() {
Here's one:
var found = true;
while(found)
{
var img = new Image();
img.src = 'path';
found = img.naturalWidth? true : false;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.