I have JS that creates dynamic elements. I want to add onclick events to these elements and pass the calling element's ID to the event handler so that I can use JS to change the text of the element that is clicked.
I do that by doing something like this inside a loop:
var btnID = "button-" + x; // unique id for changing element inside of test()
/* desired result is <button onclick="test(<runtime value of btnID>)"></button> */
buttonElement.onclick = function () { test(btnID) };
Unfortunately, the result is that every button element passes the btnID
of the last element in the loop to test()
. Can someone explain why this happens?