jQuery: How to use each starting at an index other than 0

丶灬走出姿态 提交于 2019-11-27 14:42:42

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.

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/

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!