When click on an image created from an array, both of onclick and addEventListener('click',function(){}) don't work.
I am trying to display geojson data on Google map api. With javascript, I have stored the data into an array and displayed each item successfully on Google map. The images should be clickable and display more information when clicked.
for (var i = 0; i < arrItems.length; i++) {
var image = arrItems[i].properties.image;
//create image(list_img)
var list_img = document.createElement("img");
list_img.className = "list_img card-img-top";
list_img.src = arrItems[i].properties.image;
list_img.onclick = alert(i);
list_img.addEventListener("click",function(){
console.log(i);
});
}
In the code above, if I use onclick, it alerts all the id number before the page is loaded. And no response when I click the images after the page loaded. if I user addEventListener, no matter which image clicked, it always outputs the last i number.