0

My code is:

for (i = 0; i < 3; i++) {
   elem[i].click(function(event) { alert(i); });
}

Unfortunately that does not work. Any idea how to make it alert the same i as the i in elem[i].

Thank you!

James Chen
  • 33
  • 4

1 Answers1

0

You should use let for defining variable i. Unlike var, variables defined by let are block scoped. As a result, they won't be overwritten after each iteration.

for (let i = 0; i < 3; i++) {
   elem[i].click(function(event) { alert(i); });
}

By the way, when ES6 is available, it's generally a bad idea to use closures in this case. It's kind of overkill.

Lewis
  • 14,132
  • 12
  • 66
  • 87