嵌套 jQuery.each() - 继续/中断

发布于 2024-09-10 09:10:10 字数 1239 浏览 10 评论 0 原文

考虑以下代码:

    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;
            }
        });
    });

有趣的部分是嵌套的 jQuery.each() 循环。根据 文档,返回 false 将跳出循环(停止循环的执行 -类似于普通的 JavaScript break 语句),返回非 false 将停止当前迭代并继续下一次迭代(类似于普通的 JavaScript continue 语句)。

我可以自行中断或继续 jQuery.each(),但是使用嵌套的 jQuery.each,我发现很难从子循环中脱离父循环。我可以使用布尔值,并在每次子迭代时更新它,但我想知道是否有更简单的方法。

如果您想尝试一下,我已经在 jsFiddle 设置了一个示例。只需单击“测试”按钮即可运行上面所示的示例。

TLDR: 在 jQuery 上下文中是否有类似标记的 continue 或 break 的内容?

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).

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.

I've set up an example at jsFiddle if you'd like to mess around with it. Simply click the "Test" button to run the example shown above.

TLDR: Is there anything resembling a labeled continue or break within the context of jQuery?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

郁金香雨 2024-09-17 09:10:10

这里有很多答案。它很旧,但这适用于通过谷歌来到这里的任何人。在 jQuery 中,每个函数

return false; 都类似于 break

只是

return; 就像 continue

这些将模拟中断和继续的行为。

There are a lot of answers here. And it's old, but this is for anyone coming here via google. In jQuery each function

return false; is like break.

just

return; is like continue

These will emulate the behavior of break and continue.

多情出卖 2024-09-17 09:10:10

你应该在没有 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;
        }
    }
}

您可以在这里尝试。我不确定这是否是您所追求的确切行为,但现在您不在由双 .each() 并且您可以随时 returnbreak在这种情况下想要。

You should do this without jQuery, it may not be as "pretty" but there's less going on and it's easier to do exactly what you want, like this:

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 exact behavior 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.

魂ガ小子 2024-09-17 09:10:10

正如 jQuery 文档中所述 http://api.jquery.com/jQuery.each/

jQuery.each 中的 return truecontinue 相同

return falsereturn false 相同代码>中断

As is stated in the jQuery documentation http://api.jquery.com/jQuery.each/

return true in jQuery.each is the same as a continue

return false is the same as a break

像极了他 2024-09-17 09:10:10

没有干净的方法可以做到这一点,就像上面提到的@Nick 一样,使用老式的循环方式可能会更容易,因为这样你就可以控制它。但如果你想坚持现有的,有一种方法可以解决这个问题。我确信我会为此感到兴奋。但是...

无需 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)
}

好的,让抖动开始。

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...

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:

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.

粉红×色少女 2024-09-17 09:10:10

这里的问题是,虽然您可以从 .each 回调中返回 false,但 .each 函数本身返回 jQuery 对象。所以你必须在两个级别都返回 false 来停止循环的迭代。另外,由于无法知道内部 .each 是否找到匹配项,因此我们将不得不使用带有更新闭包的共享变量。

words 的每个内部迭代都引用相同的 notFound 变量,因此我们只需在找到匹配项时更新它,然后返回它。外部闭包已经有对它的引用,因此它可以在需要时break

$(sentences).each(function() {
    var s = this;
    var notFound = true;

    $(words).each(function() {
        return (notFound = (s.indexOf(this) == -1));
    });

    return notFound;
});

您可以尝试此处的示例

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 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.

$(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.

倦话 2024-09-17 09:10:10

我为此使用了“突破”模式:

$(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;
});

这对于任何嵌套深度都适用。 breakout 是一个简单的标志。它将保持未定义状态,除非您将其设置为false(正如我在返回语句中所做的那样,如上所示)。您所要做的就是:

  1. 在最外层闭包中声明它: var breakout;
  2. 将其添加到您的 return false 语句中: return breakout = false< /code>
  3. 在外部闭包中返回突破点。

不太不优雅吧?
...无论如何对我有用。

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:

  1. declare it in your outermost closure: var breakout;
  2. add it to your return false statement(s): return breakout = false
  3. return breakout in your outer closure(s).

Not too inelegant, right?
...works for me anyway.

一紙繁鸢 2024-09-17 09:10:10

不幸的是没有。这里的问题是迭代发生在函数内部,因此它们与普通循环不同。 “中断”函数的唯一方法是返回或抛出异常。所以是的,使用布尔标志似乎是“打破”外部“循环”的唯一合理方法。

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".

惟欲睡 2024-09-17 09:10:10

返回 true 不起作用

返回 false 起作用

found = false;
query = "foo";

$('.items').each(function()
{
  if($(this).text() == query)
  {
    found = true;
    return false;
  }
});

return true not work

return false working

found = false;
query = "foo";

$('.items').each(function()
{
  if($(this).text() == query)
  {
    found = true;
    return false;
  }
});
绳情 2024-09-17 09:10:10

标记中断

outerloop:
$(sentences).each(function() 
{
    $(words).each(function(i) 
    {
        break; /* breaks inner loop */
    } 
    $(words).each(function(i)  
    {
        break outerloop; /* breaks outer loop */
    }
}

Labeled Break

outerloop:
$(sentences).each(function() 
{
    $(words).each(function(i) 
    {
        break; /* breaks inner loop */
    } 
    $(words).each(function(i)  
    {
        break outerloop; /* breaks outer loop */
    }
}
薄情伤 2024-09-17 09:10:10

确认 API 文档 http://api.jquery.com/jQuery.each/ 说:

我们可以通过使
回调函数返回 false。返回非 false 与 a 相同
for 循环中的 continue 语句;它会立即跳到下一个
迭代。

这是我的示例 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));

Confirm in API documentation http://api.jquery.com/jQuery.each/ say:

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.

and this is my example 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));
你另情深 2024-09-17 09:10:10

您可以通过使回调函数返回 false 来在特定迭代中中断 $.each() 循环。

返回非 false 与 for 循环中的 continue 语句相同;它将立即跳到下一次迭代。

You 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文