1

I am dynamically creating an onclick event for html elements that are also created dynamically. I can make the elements just fine, but when I click on a specific one, it always runs the onclick for whatever the last element created was.

var parentNode = document.getElementById('mpacks');
parentNode.innerHTML = '';
for (var i = 0, size = listOfItems.length; i < size; i++){
        var listNode = document.createElement('LI');
        var tmp = document.createElement('a');
        tmp.id = listOfItems[i];
        tmp.innerText = listOfItems[i];
        listNode.appendChild(tmp);
        parentNode.appendChild(listNode);
        tmp.onclick = function() {insertParam(listOfItems[i])};
}

For example: If I have the list [link1, link2, link3], I render them fine and they all show up on my page. When I click link 1, I would like that to be passed into the onclick function as shown... insertParam("link1"). Instead, when I click on link1, it passes in insertParam("link3") for some reason.

1 Answers1

1

This is happening because of closure. Use let instead of var in for loop

for (let i = 0, size = listOfItems.length; i < size; i++)
Vikas
  • 6,868
  • 4
  • 27
  • 41