-
-
Save Striker21/1352993 to your computer and use it in GitHub Desktop.
quickEach
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
// $.quickEach() replicates the functionality of $.each() but allows 'this' | |
// to be used as a jQuery object without the need to wrap it using '$(this)'. | |
// The performance boost comes from internally recycling a single jQuery | |
// object instead of wrapping each iteration in a brand new one. | |
// Development ----------------------------------- | |
(function($) | |
{ | |
$.fn.quickEach = function(f) | |
{ | |
var j = $([0]), i = -1, l = this.length, c; | |
while( | |
++i < l | |
&& (c = j[0] = this[i]) | |
&& f.call(j, i, c) !== false | |
); | |
return this; | |
}; | |
})(jQuery); | |
// Minified -------------------------------------- | |
(function($){$.fn.quickEach=function(f){var j=$([0]),i=-1,l=this.length,c;while(++i<l&&(c=j[0]=this[i])&&f.call(j,i,c)!==false);return this}})(jQuery); | |
// Usage ----------------------------------------- | |
(function($) | |
{ | |
$('div').quickEach(function(i, el) | |
{ | |
//'this' is a jQuery object | |
//'i' is the index | |
//'el' is the DOM element | |
//Print the index of each element | |
this.html('Index: '+i); | |
}); | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You are correct. If you plan on referencing one of the objects again you will need to wrap it if you plan on using jQuery functions on it. In that scenario, you may be better off using standard $.each().
However, if you're storing a reference to the entire collection, then quickEach is still the better option. This is what you'd do: