I am using a for loop on a data array, for each element in an array, the element's id is equal to the name of an img. For example: if the id of an element is 1, there should be a corresponding image in the image folder named as 1.
Problem: Both jpg and png format exist in the img folder, so I have to check if an image with a specific format exit or not, if it doesn't, then I have to change .jpg to .png.
I am going to use it with jQuery .on('error')  function, but the problem is .on('error') runs after the entire for loop, so every time when I try to get the id, I get the last element of an array.
Code :
for (var i = 0; i < organisers_data.length; i++) {
  console.log("current ID" + organisers_data[i].id);
  organ_data_id = organisers_data[i].id.replaceAll(/^0+(?!$)/g, "");
  var imgPath = '<img src="/assets/images/organisers/' + organ_data_id + '.jpg" />';
  console.log("before" + imgPath)
  $(imgPath).on('error', function(e) {
    imgPath = '<img src="/assets/images/organisers/' + organ_data_id + '.png" />';
  });
  var tableDiv = '';
  tableDiv +=
    '<div>' +
    '<a href="">' +
    imgPath +
    '</a>' +
    '</div>';
  if ($('.organisers_table')) {
    $('.organisers_table').append(tableDiv)
  }
}
}
console shows that
$(imgPath).on('error', function(e) {
    imgPath = '<img src="/assets/images/organisers/' + organ_data_id + '.png" />';
});
only take the last element id ,seems the on function work only after the for loop, but what I want is id of an element in each loop, what should I do?
 
     
     
    