I have a list of elements and I'd like to add a click event to each one that will call a function and pass it an index of a list. In the case below I'm defining itemIndex
as 0 and incrementing it each loop. When the click event is called the index it uses is 3
(number of loops +1) instead of the number of the loop. How can I solve this problem?
let itemIndex = 0;
itemList.forEach(item => {
const itemFragment = document.importNode(this.itemTemplate.content, true);
//add click event
itemFragment.querySelector('.part').addEventListener('click', () => {
loadItem(itemList[itemIndex]);
});
//append product to body row
itemTarget.appendChild(itemFragment);
itemIndex++;
});