0

I am dynamically creating a series of buttons using a for loop and adding an Event Listener to them as follows (I have excluded several lines of code for simplicity). However, upon using any of the buttons after creation, the parameter "i" always corresponds to the value "i" had when it exited the for loop. I have seen numerous proposed solutions online, but none of them are actually working.

 for (var i = 0; i < size; i++) {
    button.addEventListener('click', () => this.Purchase(i))
 }
JF0001
  • 819
  • 7
  • 30

1 Answers1

1

You should use let i = 0 instead of var i = 0 in order to have the i variable be scoped to the loop. With var, i is scoped to the innermost function, which means it constantly gets overwritten. See here for more info.

Aplet123
  • 33,825
  • 1
  • 29
  • 55