I have a collection of elements that I want to loop over using each, but I am looping over them inside an outer for loop. When I find what I want in the each, I return false
Another possibility is to store the index unincremented, then you can use the gt selector to directly select elements which occur after the stored index, like this:
$('#someElemID .someClass:gt(' + storedIndex + ')').each(function() {
...
I don't know how often you are going to run this or how many different varitions you need, but I'm not fond of leaving nextValue floating around in space. You could do something like this, which would give you the availability to create multiple different 'queues' if you will. It sounds like you only want to find that item once, and once you do you never want to search it again. This should do just that, and it works by caching the selector. If you are changing the DOM between calls, use one of the other answers.
nameThisFunction = function(s) {
var self = this;
this.selector = $(s);
return function(searchFor) {
self.selector.each(function(i) {
if (/*Do your comparision to searchFor*/) {
// Do what you want
self.selector.splice(i, 1);
return false;
}
});
}
};
var thisQueue = new nameThisFunction('#someElemId .someClass');
thisQueue('Search for something here');
Here's an example fiddle: http://jsfiddle.net/robert/RCfeJ/
Use slice() http://api.jquery.com/slice/
$('#someElemID').find('.someClass').slice(nextIndex).each( ...
btw if the elements are static, consider caching:
var $elms = $('.someClass', '#someElemID'),
nextIndex = 0;
for (var j = 1; j <= someCount; j++) {
// do outside loop stuff
$elms.slice(nextIndex).each(function(index) {
if (/*this is right one*/) {
nextIndex = index + 1;
return false;
}
});
}
That should improve performance considerably.