I send an ajax request to my server. I then receive an object. The object looks likes this:
{
"payload": {
"result": [
"http://example.com/img1.jpg",
"http://example.com/img2.jpg",
"http://example.com/img3.jpg",
"http://example.com/img4.jpg",
"http://example.com/img5.jpg"
]
}
}
I then traverse the object using a for loop
if (typeof response.payload.result == 'object') {
var ln = response.payload.result.length;
var i;
if (ln > 0) {
for (i = 0; i < ln; i++) {
/* this shows i was increased for every iteration */
console.log(i);
var current_img = response.payload.result[i];
var img = $("<img />").attr('src', current_img)
.load(function () {
console.log(i);
/* this logs the last iteration 4 times */
$("#product-images").append(img);
});
}
}
}
My problem is that only (1) image element is being created. The single element being appended to the DOM after this code executes is the value of the last element in the array. Why is jQuery.load() only being called on the last iteration?