jQuery:如何使用以0以外的索引开头的每个 [英] jQuery: How to use each starting at an index other than 0

查看:89
本文介绍了jQuery:如何使用以0以外的索引开头的每个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要使用每个元素循环的元素集合,但是我正在外部for循环中循环它们.当我在每一个中找到想要的东西时,我返回false进行突破.下次外部循环运行时,我想从返回的元素之后的元素开始.通用代码示例:

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 to break out. The next time the outer loop runs, I want to start in the each at the element after the one I returned at. A generic code example:

var nextIndex = 0;

for (var j=1; j <= someCount; j++) {
    // do outside loop stuff

    $('#someElemID').find('.someClass').each(function(index) {
        if (/*this is right one*/) {
            // do something
            // next index should get passed to each function next loop... somehow?
            nextIndex = index + 1; 
            return false;
        }
    });
}

我曾考虑过切换到for循环,但是后来我对如何访问.find('.someClass')的返回值感到困惑.也许这本身就是一个单独的问题...

I thought about switching to a for loop, but then I got confused as to how to access the return from the .find('.someClass'). Maybe that's a separate question itself...

这很明显吗?

推荐答案

使用slice() http://api.jquery.com/slice/

$('#someElemID').find('.someClass').slice(nextIndex).each( ...  


btw如果元素是静态的,请考虑缓存:


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.

这篇关于jQuery:如何使用以0以外的索引开头的每个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆