News for hackers. Stuff that matters.
Re:How do JavaScript closures work? by anc2020 on Thursday June 23, 2011 @11:56AM (#2688339)
I'm not sure your code does as intended, won't the function be called only once the element is clicked?

This should work okay:

  for (var i = 0; i < 5; i++) {
    $(DOMelement:eq(i)).click((function(i) {
     return function() {
      console.info(i);
     }
    }(i)));
  }
Also surely DOMelement.eq(i) as opposed to DOMelement:eq(i)?
Re:How do JavaScript closures work? by sdevlin on Thursday June 23, 2011 @12:11PM (#2688414)
I think you're correct. His interior function is still just another closure around the original var i.

Also, this feels like piling on, but I think the original (intentionally erroneous) example would print '5' repeatedly rather than '4'. var i ends up with the value 5.

Re:How do JavaScript closures work? by csomar on Thursday June 23, 2011 @05:09PM (#2689895)
Yes, you are correct (I can't edit right now). You need to return a new function, and a reference actually.

for DOM part, I didn't understand your question. However, the right way to do it is

  $(DOMelement:eq(i)).each();
to iterate through each element.