如何跳出jQuery的 each
循环?
我已经尝试了:
return false;
在循环中但这并没有起作用。有什么想法吗?
更新于2020年9月5日
我把return false;
放错了位置。当我将其放在循环内部时,一切都正常工作了。
$.each
或 $(selector).each
循环,你需要在循环回调函数中返回 false
。如果返回 true
,它将跳过当前迭代,相当于普通循环中的 continue
。$.each(array, function(key, value) {
if(value === "foo") {
return false; // breaks
}
});
// or
$(selector).each(function() {
if (condition) {
return false;
}
});
$().each
中跳出的方法完全相同,您的编辑只会导致混淆。 - Jake我们可以通过使回调函数返回false来终止$.each()循环。
在回调函数中返回false:
function callback(indexInArray, valueOfElement) {
var booleanKeepGoing;
this; // == valueOfElement (casted to Object)
return booleanKeepGoing; // optional, unless false
// and want to stop looping
}
顺便说一句,continue
的作用如下:
返回非false值与在for循环中使用continue语句相同,将立即跳到下一次迭代。
我遇到了一种情况,满足某个条件后跳出循环,但是在 .each() 函数后的代码仍然执行。所以我设置了一个标志位为“true”,并在 .each() 函数之后立即检查标志位,以确保不再执行后续代码。
$('.groupName').each(function() {
if($(this).text() == groupname){
alert('This group already exists');
breakOut = true;
return false;
}
});
if(breakOut) {
breakOut = false;
return false;
}
针对这个问题,我创建了一个Fiddle来回答,因为已经接受的答案是不正确的,而且这是谷歌返回的第一个StackOverflow主题与此问题相关。
要退出$.each,必须使用return false;
这里有一个证明它的Fiddle:
我知道这是一个比较老的问题,但我没有看到任何回答能够解释为什么和何时可以用return打破循环。
我想用两个简单的例子来解释:
1. 例子: 在这种情况下,我们有一个简单的迭代,如果我们找到了三,我们想用return true来打破循环。
function canFindThree() {
for(var i = 0; i < 5; i++) {
if(i === 3) {
return true;
}
}
}
function canFindThree() {
var result = false;
$.each([1, 2, 3, 4, 5], function(key, value) {
if(value === 3) {
result = true;
return false; //This will only exit the anonymous function and stop the iteration immediatelly.
}
});
return result; //This will exit the function with return true;
}
"each"使用回调函数。 无论调用函数如何,回调函数都会执行,因此从回调函数返回到调用函数是不可能的。
如果您需要基于某些条件停止循环执行并保留在同一函数中,请使用for循环。
$(document).on('click', '#save', function () {
var cont = true;
$('.field').each(function () {
if ($(this).val() === '') {
alert('Please fill out all fields');
cont = false;
return false;
}
});
if (cont === false) {
return false;
}
/* commands block */
});
如果 cont 不是 false,则执行命令块。
return false
放错地方了。当我修正后,一切都正常了。 - Luke101return false
与$().each
不兼容 - 因为它是可以的。 - But those new buttons though..