In Javascript, I have an array of strings that I need to use for loading images on my page through AJAX. After each image is loaded, there are additional tasks to be performed which include sending a HTTP request to delete the image.
Below is the code I currently have:
for (x in images) {
var img = new Image();
$(img)
.load(function(){
$('#image_'+images[x]).html(''); //remove loading gif
$('#image_'+images[x]).append(this);
$.post('/images/destroy_image',{id:images[x]});
})
.attr('src', '/images/get_image?id='+images[x]);
}
The issue arises when there is more than one string in the images
array. When an image finishes loading and its load
function runs, any reference to images[x]
now points to the last string in the images
array instead of its original value during the loop execution.
For example:
If images
is {'12','100'}, when the first image finishes loading, the line in its load
function will read
$('#image_100').html('');
instead of
$('#image_12').html('');
How can this be resolved?