I have the following code which suppose to load couple of images and then to fade them. But instead to load all images on each fade it loads the same image every time. Does anyone have any idea?
http://jsfiddle.net/7kacz43o/8/
var img, i,
imageCount = [1,2,3,4],
div = document.getElementById('foo');
console.log(imageCount.length);
for(i = 1; i <= imageCount.length; i++){
img = new Image();
img.onload = function() {
div.appendChild(img);
};
img.src = 'http://tdhdemo.com/frames/frame_' + i + '.jpg';
img.id = "top";
}
You reuse img
inside onload
, which means when the for
runs for the next index, img
will be overwritten. In the onload
event only the last img
will be appended to the div (4 times, but that results in one image tag).
Since you attach the onload
function on the img
itself, you can use this
to reference the image:
img.onload = function() {
div.appendChild(this);
};
Another recommendation: Instead of using an array and its length
to power your for
loop, why not use a count variable directly?
var imageCount = 4;
...
for (i = 1; i <= imageCount; i++) {
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.