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?
2
Answers
You can create the element and use the event listener to change the source of the image.
Create a fileExists function. I borrowed this from https://stackoverflow.com/a/13989063/1152809
Loop through the array like a boss, using
.map
instead offor
.Each iteration of the array will create the same html as your code above, but now with more readability.
Join the elements of the resultant array into one string into the table_div variable.
Note: My solution uses String Literals aka Template Literals to produce strings. No need for the
+
mess. Basically instead of quotes, use tic marks, then insert variables or really any js inside${}
, like so: