0

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);
  }
Shophaune
  • 5
  • 5

2 Answers2

0

What about if you use let to declare your i variable:

document.getElementById("mylist").innerHTML = "";
for (let 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);
}

Reference: 'let' vs 'var' in javascript for loops, does it mean that all the for loops using the 'var i =0' should actually be 'let i =0' instead?

Paolo Carrara
  • 394
  • 4
  • 13
0

You have to try as below to capture variable inside for loop to set event listener. Find Creating closures in loops: A common mistake in this document.

Update your event listener assignment as li.addEventListener("click", function(){ var index = i; return foo(index); });.

Complete code is as 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(){ var index = i; return foo(index); });
    document.getElementById("mylist").appendChild(li);
}
Karan
  • 12,059
  • 3
  • 24
  • 40