0

I am new in JavaScript and jQuery. I have found a problem which I can't solve myself.

for (i = 0; i < 12; i++)
{
    $("#c" + i).on("click", function () { alert(i) });
}

It attaches events to every element with id from c0 to c11 with alert(12) instead of alert(i)...

On the other hand

$("#c0").on("click", function () { alert(0) });
$("#c1").on("click", function () { alert(1) });
$("#c2").on("click", function () { alert(2) });
...

Works good. Isn't it the same?

1 Answers1

1

This is because of the way var keyword works and also because

$("#c" + i).on("click", function () { alert(i) });`

is async in nature.

just do this instead,

Quick Fix

for (let i = 0; i < 12; i++)
 {
   $("#c" + i).on("click", function () { alert(i) });
 }

Explanation: Your code does not work because $('#c').on('click', fun) is async in nature what that means is this function function () { alert(i) } will be executed later in time, by the time that happens your for loop will be finished with the value of i = 12 hence, you are getting 12 as a value for all handlers.

Now the question is how adding let fixed this?

The answer is simple, Let follows Block scoping whereas var or no var ( global ) is not blocked scoped. var has a functional scope and to achive the same with var you'll need to do something like this.

for(var i = 0; i < 12; i++) {
  (function(i) {
    $("#c" + i).on("click", function () { alert(i) });
  })(i);
}
priyansh gupta
  • 293
  • 1
  • 12
  • Thanks! That works like a charm! So it's all about "cloning" the value from iterator. Sorry, looks like rookie mistake, but it's my second day in JS, and I wasn't able to find solution here and on google :) – Sebastian Z. Apr 03 '18 at 12:45
  • “async in nature”? That’s a confusing way of saying that the function is run at a later point in time where the function-scoped `var` has already changed. After all, you wouldn’t call `let` “synchronous in nature”, would you? The issue is _just_ the `var`. – Sebastian Simon Apr 03 '18 at 12:45
  • @Xufox I agree that was a confusing way of saying it. I have fixed it though. – priyansh gupta Apr 03 '18 at 13:05