Think about it: what if you had three links, for example:
<a href="#">0</a> <a href="#">1</a> <a href="#">2</a>
You want them to display their number when you click on them, so do the following:
var links = $('a'); for (var i = 0; i < links.length; i++) { links[0].onclick = function () { alert(i); } }
At first glance, you expect that, for example, since you assigned a click handler to the first link when i = 0 , it will warn 0 when you click on it. However, when you click on it, it will warn 3 .
You said it yourself, your code creates a closure. What the above code does is that it assigns a function handler to the click event for each link. Each of these function handlers maintains a reference to the variable i (note: not the current value!).
The moment you assign a function handler, it does not actually evaluate what value i (because it does not need it). When you press, aha, this is when he checks that i is the value and warns about it.
When you click the link, the for loop will be long, with i = 3 and what your click handler warns about.
source share