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

JavaScript

樱凯

2020-03-11

我有一些代码:

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

如何根据条件从“每个”代码块中退出?

更新:

如果我们有这样的事情怎么办:

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

是否有可能从内部的“每个”功能中同时脱离这两个“每个”功能?

#19.03.2013

如果您想继续而不是爆发

return true;

第820篇《如何从JQuery中的each()函数中断/退出?\[重复\]》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
古一古一 2020.03.11
if (condition){ // where condition evaluates to true 
    return false
}

看到3天前问的类似问题

番长千羽 2020.03.11

您可以使用 return false;

+----------------------------------------+
| JavaScript              | PHP          |
+-------------------------+--------------+
|                         |              |
| return false;           | break;       |
|                         |              |
| return true; or return; | continue;    |
+-------------------------+--------------+
宝儿神无 2020.03.11

从匿名函数返回false:

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

每种方法的文档中

从每个函数中返回“ false”将完全停止所有元素的循环(这就像在常规循环中使用“ break”一样)。从循环内返回“ true”会跳到下一个迭代(这就像对正常循环使用“ continue”一样)。

null 2020.03.11

根据文档,您可以简单return false;地中断:

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

    if (iWantToBreak)
        return false;
});

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android