退出jQuery循环

时间:2014-12-31 21:26:14

标签: javascript jquery

这个jQuery代码循环遍历表中的行,并在其前进时突出显示每一行。 我有一个停止按钮,将变量设置为false。

我知道我可以使用return false;突破.each循环,但我希望它能从队列中突破。

如果varfalse

,我该怎么办?
$('.js-channel-notes tr').each(function(i) {
    $(this).delay((i++) * 160).queue(function() {
        $('.channel-row-highlight').removeClass('channel-row-highlight');
        $(this).addClass('channel-row-highlight').clearQueue();
    });
});

2 个答案:

答案 0 :(得分:1)

请勿使用.each().queue()。只需创建一个对当前元素进行操作的函数,并将下一次调用的执行延迟到同一函数。

当前元素由您在每次调用时递增的i计数器确定。

要打破它,请检查一个标志以立即退出该功能。

var tr = $('.js-channel-notes tr');
var i = 0;
var halt;

function next() {
    if (halt) return;

    $('.channel-row-highlight').removeClass('channel-row-highlight');
    tr.eq(i).addClass('channel-row-highlight');
    i++;
    if (i < tr.length) {
        setTimeout(next, 160);
    }
}

next();

或者完全跳过jQuery,因为那里很少使用jQuery。

var tr = document.querySelectorAll('.js-channel-notes tr');
var i = 0;
var halt;

function next() {
    if (halt) return;

    var c = document.querySelector('.channel-row-highlight');
    if (c) c.classList.remove('channel-row-highlight');
    tr[i].classList.add('channel-row-highlight');
    i++;
    if (i < tr.length) {
        setTimeout(next, 160);
    }
}

next();

使用.delay().queue()所需的工程量远远超过了所需的工程量。更简单更好。

答案 1 :(得分:0)

显然,你不想要each

你想要一个延续,你可以有条件地&#39;继续。基本上是这样的(但未经检查,未运行):

var continuation = function(todo) {
    if (!todo.length) return;
    var head = todo[0];
    var tail = todo.slice(1); // or what is it
    head.delay(...).queue(function(){
         if (somecondition)
             continuation(tail);
    });
};
continuation($('.js-channel-notes tr'));