var selector = '';
$.each(data, function(key, val) {
var img = '/wp-content/img/history/' + val.image_id + '.jpg';
selector = '#img'+(key+1);
$(selector).prepend('<img id src=' + img + ' alt="pic" />');
});
The above code snippet works, the images are loaded into the elements #img1, #img2, #img3, #img4. I cannot be sure the images exist so a .done/.fail was added to the file get.
var selector = '';
$.each(data, function(key, val) {
var img = '/wp-content/img/history/' + val.image_id + '.jpg';
selector = '#img' + (key + 1);
$(selector).removeClass('d-none');
$.get(img).done(function() {
$(selector).empty();
$(selector).prepend('<img id src=' + img + ' alt="pic" />');
}).fail(function() {
alert(val.image_id + ' not found');
});
});
After done/.fail on the file get are added 'key' is no longer being incremented. Using a counter within the loop behaves the same way as 'Key'.
Does anyone have an insight as to the cause?
$.get()call in the second example is asynchronous. This means that the logic indone()/fail()occurs long after the$.each()loop has completed. Therefore theselectorvalue will only ever be what it was set to in the final iteration of the loop. The quick way to fix this is to use a closure. The best practice way to fix this is to stop making AJAX requests in a loop....imgloads or not. In which case use aloadanderrorevent handler on theimgelements (something like this) instead of AJAX. Better still, sanitise the input data and/or change the process logic so that there cannot possibly be any dead image links in the logic.