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

前端 未结 3 593
萌比男神i
萌比男神i 2020-12-03 14:47

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

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-03 15:05

    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.

提交回复
热议问题