Skip to content

Instantly share code, notes, and snippets.

@mcsheffrey
Created April 29, 2012 20:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcsheffrey/2552977 to your computer and use it in GitHub Desktop.
Save mcsheffrey/2552977 to your computer and use it in GitHub Desktop.
jQuery each, for and closure
// OMG I heard jQuery.fn.each was like a HUGE perf hit!
// So I'm going to use a native for loop instead!
var lis = $("li"),
l = lis.length, // 5
li;
for (var i=0;i<l;i++) {
li = lis.eq(i);
li.click(function() {
alert("You clicked the "+ i +"th item");
// No matter which item is clicked, it always alerts 5!
});
}
var lis = $("li"), l = lis.length, i = 0, li;
for (i=0;i<l;i++) {
(function(i) {
// i is now local to this IIFE (immediately-invoked function expression)
li = lis.eq(i);
li.click(function() {
alert("You clicked the "+ i +"th item");
});
})(i);
}
// Just use jQuery's .each, it's not actually a serious performance concern
lis.each(function(i,elem) {
$(this).click(function(event) {
alert("jQuery's each says you clicked the "+ i +"th item");
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment