如何从JQuery中的each()函数中断/退出? [重复]

本文翻译自:How to break/exit from a each() function in JQuery? [duplicate]

This question already has an answer here: 这个问题已经在这里有了答案:

I have some code: 我有一些代码:

$(xml).find("strengths").each(function() {
   //Code
   //How can i escape from this block based on a condition.
});

How can i escape from the "each" code block based on a condition? 如何根据条件从“每个”代码块中退出?

Update: 更新:

What if we have something like this: 如果我们有这样的事情怎么办:

$(xml).find("strengths").each(function() {
   $(this).each(function() {
       //I want to break out from both each loops at the same time.
   });
});

Is it possible to break out from both "each" functions from the inner "each" function? 是否有可能从内部的“每个”功能中同时脱离这两个“每个”功能?

# 19.03.2013 #19.03.2013

If you want to continue instead of break out 如果您想继续而不是爆发

return true;

#1楼

参考:https://stackoom.com/question/7Y4i/如何从JQuery中的each-函数中断-退出-重复


#2楼

You can use return false; 您可以使用return false;

+----------------------------------------+
| JavaScript              | PHP          |
+-------------------------+--------------+
|                         |              |
| return false;           | break;       |
|                         |              |
| return true; or return; | continue;    |
+-------------------------+--------------+

#3楼

According to the documentation you can simply return false; 根据文档,您可以简单地return false; to break: 打破:

$(xml).find("strengths").each(function() {

    if (iWantToBreak)
        return false;
});

#4楼

Return false from the anonymous function: 从匿名函数返回false:

$(xml).find("strengths").each(function() {
  // Code
  // To escape from this block based on a condition:
  if (something) return false;
});

From the documentation of the each method : 每种方法的文档中:

Returning 'false' from within the each function completely stops the loop through all of the elements (this is like using a 'break' with a normal loop). 从每个函数中返回“ false”将完全停止所有元素的循环(这就像在正常循环中使用“ break”一样)。 Returning 'true' from within the loop skips to the next iteration (this is like using a 'continue' with a normal loop). 从循环内返回“ true”会跳到下一个迭代(这就像对正常循环使用“ continue”一样)。


#5楼

if (condition){ // where condition evaluates to true 
    return false
}

see similar question asked 3 days ago. 看到3天前问的类似问题

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值