嵌套的 jQuery.each() - 继续/中断
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3267508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Nested jQuery.each() - continue/break
提问by Ryan Kinal
Consider the following code:
考虑以下代码:
var sentences = [
'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
'Vivamus aliquet nisl quis velit ornare tempor.',
'Cras sit amet neque ante, eu ultrices est.',
'Integer id lectus id nunc venenatis gravida nec eget dolor.',
'Suspendisse imperdiet turpis ut justo ultricies a aliquet tortor ultrices.'
];
var words = ['ipsum', 'amet', 'elit'];
$(sentences).each(function() {
var s = this;
alert(s);
$(words).each(function(i) {
if (s.indexOf(this) > -1)
{
alert('found ' + this);
return false;
}
});
});
The interesting part is the nested jQuery.each() loops. As per the documentation, returning false will break out of the loop (discontinuing execution of the loop - similar to a normal JavaScript break statement), and returning non-false will stop the current iteration and continue with the next iteration (similar to a normal JavaScript continue statement).
有趣的部分是嵌套的 jQuery.each() 循环。根据文档,返回 false 将跳出循环(停止循环的执行 - 类似于普通的 JavaScript break 语句),返回非 false 将停止当前迭代并继续下一次迭代(类似于正常的JavaScript continue 语句)。
I can break or continue a jQuery.each() on its own, but with nested jQuery.each, I've found it difficult to break out of the parent loop from within the child loop. I could use a boolean value, and update it on every child iteration, but I was wondering if there was an easier way.
我可以自己中断或继续一个 jQuery.each(),但是对于嵌套的 jQuery.each,我发现很难从子循环中跳出父循环。我可以使用布尔值,并在每次子迭代时更新它,但我想知道是否有更简单的方法。
I've set up an example at jsFiddleif you'd like to mess around with it. Simply click the "Test" button to run the example shown above.
如果你想弄乱它,我已经在 jsFiddle设置了一个例子。只需单击“测试”按钮即可运行上面显示的示例。
TLDR:Is there anything resembling a labeled continue or break within the context of jQuery?
TLDR:在 jQuery 的上下文中是否有类似于标记的 continue 或 break 的东西?
采纳答案by Nick Craver
You should do this withoutjQuery, it may not be as "pretty" but there's less going on and it's easier to do exactly what you want, like this:
您应该在没有jQuery 的情况下执行此操作,它可能不那么“漂亮”,但是发生的事情较少,并且更容易完全按照您的意愿去做,如下所示:
var sentences = [
'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
'Vivamus aliquet nisl quis velit ornare tempor.',
'Cras sit amet neque ante, eu ultrices est.',
'Integer id lectus id nunc venenatis gravida nec eget dolor.',
'Suspendisse imperdiet turpis ut justo ultricies a aliquet tortor ultrices.'
];
var words = ['ipsum', 'amet', 'elit'];
for(var s=0; s<sentences.length; s++) {
alert(sentences[s]);
for(var w=0; w<words.length; w++) {
if(sentences[s].indexOf(words[w]) > -1) {
alert('found ' + words[w]);
return;
}
}
}
You can try it out here. I'm not sure if this is the exactbehavior you're after, but now you're not in a closure inside a closure created by the double .each()
and you can return
or break
whenever you want in this case.
你可以在这里试一试。我不确定这是否是您所追求的确切行为,但是现在您不在由 double 创建的闭包内的闭包中,.each()
并且在这种情况下,您可以return
或break
任何时候都可以。
回答by Thihara
There are a lot of answers here. And it's old, but this is for anyone coming here via google. In jQuery each function
这里有很多答案。它很旧,但这是为任何通过谷歌来到这里的人准备的。在 jQuery 中的每个函数
return false;
is like break
.
return false;
就像break
.
just
只是
return;
is like continue
return;
就好像 continue
These will emulate the behavior of break and continue.
这些将模拟 break 和 continue 的行为。
回答by Serj Sagan
As is stated in the jQuery documentation http://api.jquery.com/jQuery.each/
正如 jQuery 文档中所述http://api.jquery.com/jQuery.each/
return true
in jQuery.each
is the same as a continue
return true
injQuery.each
与 a 相同continue
return false
is the same as a break
return false
是一样的 break
回答by spinon
There is no clean way to do this and like @Nick mentioned above it might just be easier to use the old school way of loops as then you can control this. But if you want to stick with what you got there is one way you could handle this. I'm sure I will get some heat for this one. But...
没有干净的方法可以做到这一点,就像上面提到的@Nick 一样,使用老式循环方式可能会更容易,因为这样你就可以控制它了。但是如果你想坚持你所得到的东西,你可以用一种方法来处理这个问题。我敢肯定我会为这件热气腾腾的。但...
One way you could do what you want without an if statement is to raise an error and wrap your loop with a try/catch block:
在没有 if 语句的情况下你可以做你想做的一种方法是引发错误并用 try/catch 块包装你的循环:
try{
$(sentences).each(function() {
var s = this;
alert(s);
$(words).each(function(i) {
if (s.indexOf(this) > -1)
{
alert('found ' + this);
throw "Exit Error";
}
});
});
}
catch (e)
{
alert(e)
}
Ok, let the thrashing begin.
好的,让颠簸开始。
回答by Anurag
The problem here is that while you can return false from within the .each
callback, the .each
function itself returns the jQuery object. So you have to return a false at both levels to stop the iteration of the loop. Also since there is not way to know if the inner .each
found a match or not, we will have to use a shared variable using a closure that gets updated.
这里的问题是,虽然您可以从.each
回调中返回 false ,但.each
函数本身返回 jQuery 对象。因此,您必须在两个级别都返回 false 以停止循环的迭代。此外,由于无法知道内部是否.each
找到匹配项,我们将不得不使用共享变量使用更新的闭包。
Each inner iteration of words
refers to the same notFound
variable, so we just need to update it when a match is found, and then return it. The outer closure already has a reference to it, so it can break
out when needed.
的每次内部迭代都words
引用同一个notFound
变量,因此我们只需要在找到匹配项时更新它,然后返回它。外部闭包已经有一个对它的引用,所以它可以break
在需要时退出。
$(sentences).each(function() {
var s = this;
var notFound = true;
$(words).each(function() {
return (notFound = (s.indexOf(this) == -1));
});
return notFound;
});
You can try your example here.
回答by joneit
I've used a "breakout" pattern for this:
我为此使用了“突破”模式:
$(sentences).each(function() {
var breakout;
var s = this;
alert(s);
$(words).each(function(i) {
if (s.indexOf(this) > -1)
{
alert('found ' + this);
return breakout = false;
}
});
return breakout;
});
This works nicely to any nesting depth. breakout
is a simple flag. It will stay undefined
unless and until you set it to false
(as I do in my return statement as illustrated above). All you have to do is:
这适用于任何嵌套深度。breakout
是一个简单的标志。undefined
除非并且直到您将其设置为false
(就像我在上面的 return 语句中所做的那样),否则它将一直存在。您所要做的就是:
- declare it in your outermost closure:
var breakout;
- add it to your
return false
statement(s):return breakout = false
- return breakout in your outer closure(s).
- 在最外面的闭包中声明它:
var breakout;
- 将其添加到您的
return false
声明中:return breakout = false
- 在您的外闭包中返回突破。
Not too inelegant, right? ...works for me anyway.
不会太不雅吧?...反正对我有用。
回答by misima
return truenot work
返回 true不起作用
return falseworking
返回假工作
found = false;
query = "foo";
$('.items').each(function()
{
if($(this).text() == query)
{
found = true;
return false;
}
});
回答by casablanca
Unfortunately no. The problem here is that the iteration happens inside functions, so they aren't like normal loops. The only way you can "break" out of a function is by returning or by throwing an exception. So yes, using a boolean flag seems to be the only reasonable way to "break" out of the outer "loop".
抱歉不行。这里的问题是迭代发生在函数内部,所以它们不像普通循环。您可以“中断”函数的唯一方法是返回或抛出异常。所以是的,使用布尔标志似乎是“打破”外部“循环”的唯一合理方法。
回答by Leonardo Ciaccio
Confirm in API documentation http://api.jquery.com/jQuery.each/say:
在 API 文档http://api.jquery.com/jQuery.each/ 中确认说:
We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
我们可以通过使回调函数返回 false 来在特定迭代中中断 $.each() 循环。返回非 false 与 for 循环中的 continue 语句相同;它将立即跳到下一次迭代。
and this is my example http://jsfiddle.net/r6jqP/
这是我的例子http://jsfiddle.net/r6jqP/
(function($){
$('#go').on('click',function(){
var i=0,
all=0;
$('li').each(function(){
all++;
if($('#mytext').val()=='continue')return true;
i++;
if($('#mytext').val()==$(this).html()){
return false;
}
});
alert('Iterazione : '+i+' to '+all);
});
}(jQuery));
回答by capdragon
Labeled Break
标记中断
outerloop:
$(sentences).each(function()
{
$(words).each(function(i)
{
break; /* breaks inner loop */
}
$(words).each(function(i)
{
break outerloop; /* breaks outer loop */
}
}