此 jQuery 代码循环遍历表中的行并突出显示每一行。 我有一个停止按钮,可将变量设置为 false。
我知道我可以通过使用 return false;
来打破 .each 循环,但我希望它从队列中打破。
如果 var
为 false
,我该如何执行此操作?
$('.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();
});
});
最佳答案
不要使用.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,因为那里用得很少。
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()
所需的工程量要多得多。越简单越好。
关于javascript - 退出 jQuery 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27726447/