Having some trouble adding click events to multiple dynamically created div elements.
After creating divs with ids a0 through an, I want to assign them click events using a for loop. The problem is that when the click event occurs, I can't identify which div triggered it. The code snippet below demonstrates this issue. Essentially, #a + i always references the last div instead of the one clicked.
$(document).ready(function () {
traverse(oo);
for (i = 0; i <= groupNum; i += 1) {
$("#a" + i).click(function () {
console.log("#a" + i + "clicked");
});
}
});
I considered using a closure function, but that might overcomplicate things. Any suggestions on how to approach this more effectively?
Appreciate any help in advance.