I have an ordered list whose list items are generated using Javascript (as the number of items/their contents is variable), and I would like to add an event listener to each item dependant on which element of the list it is - so I want the 1st item to call foo(1)
, the 2nd element to call foo(2)
, the 30th element to call foo(30)
, etc. However, currently all elements are ending up with a listener identical to that of the last element. Code I'm using is shown below:
document.getElementById("mylist").innerHTML = "";
for (i = 0; i < listitems.length; i++) {
var li = document.createElement("li");
li.setAttribute("id", "listitem" + i);
li.addEventListener("click",function(){foo(i)})
document.getElementById("mylist").appendChild(li);
}