Created
April 29, 2012 20:05
-
-
Save mcsheffrey/2552977 to your computer and use it in GitHub Desktop.
jQuery each, for and closure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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