如何跳出 jQueryeach
循环?
我试过了:
return false;
在循环中,但这不起作用。有任何想法吗?
2020 年 9 月 5 日更新
我放return false;
错地方了。当我把它放在循环中时,一切正常。
对于or循环,您必须在循环回调中break
返回。$.each
$(selector).each
false
返回true
跳到下一次迭代,相当于continue
正常循环中的 a。
$.each(array, function(key, value) {
if(value === "foo") {
return false; // breaks
}
});
// or
$(selector).each(function() {
if (condition) {
return false;
}
});
我们可以通过让回调函数返回 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() 函数之后的代码仍然执行。然后我将一个标志设置为“真”,并在 .each() 函数之后立即检查该标志,以确保后面的代码没有被执行。
$('.groupName').each(function() {
if($(this).text() == groupname){
alert('This group already exists');
breakOut = true;
return false;
}
});
if(breakOut) {
breakOut = false;
return false;
}
我为这个问题的答案创建了一个 Fiddle,因为接受的答案不正确,而且这是从 Google 返回的关于这个问题的第一个 StackOverflow 线程。
要突破 $.each 您必须使用return false;
这是一个小提琴证明它:
我知道这是一个相当古老的问题,但我没有看到任何答案,这阐明了为什么以及何时可以打破回报。
我想用两个简单的例子来解释它:
1. 示例: 在这种情况下,我们有一个简单的迭代,如果我们能找到三个,我们想用 return true 中断。
function canFindThree() {
for(var i = 0; i < 5; i++) {
if(i === 3) {
return true;
}
}
}
如果我们调用这个函数,它只会返回 true。
2. 示例 在这种情况下,我们要使用 jquery 的each 函数进行迭代,该函数以匿名函数为参数。
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;
}
“每个”使用回调函数。回调函数执行与调用函数无关,因此无法从回调函数返回到调用函数。
如果您必须根据某些条件停止循环执行并保持在同一个函数中,请使用 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 运行命令块