【问题标题】:Get return from javascript anonymous funcion in each loop(s)在每个循环中从 javascript 匿名函数获取返回
【发布时间】:2015-08-29 08:33:43
【问题描述】:

以前没用过js,现在遇到问题,接下来怎么办?

function test()
{
    $(xml).find("strengths").each(function() 
    {
        $(this).each(function() 
        {
            (if some condition)
            {
                 //I want to break out from both each loops at the same time here.
                 // And from main function too!
            }
        });
    });
}

我知道要停止一个循环,我只需要return false。但是如果我有一些嵌套怎么办?以及如何从主函数返回?

谢谢大家!

【问题讨论】:

    标签: javascript jquery loops each


    【解决方案1】:

    您可以使用临时变量,如下所示:

    function test () {
        $(xml).find("strengths").each(function() {
            var cancel = false;
    
            $(this).each(function() {
                (if some condition) {
                    cancel = true;
                    return false;
                }
            });
    
            if (cancel) {
                return false;
            }
        });
    }
    

    【讨论】:

      【解决方案2】:

      你可以使用两个变量:

      function test()
      {
          var toContinue = true,
              toReturn;
          $(xml).find("strengths").each(function() 
          {
              $(this).each(function() 
              {
                  if("some condition")
                  {
                      toReturn = {something: "sexy there!"};
                      return toContinue = false;
                  }
              });
              return toContinue;
          });
      
          if(toReturn) return toReturn;
          //else do stuff;
      }
      

      【讨论】:

      • 谢谢,这正是我需要的!
      猜你喜欢
      • 2011-11-05
      • 1970-01-01
      • 1970-01-01
      • 2012-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多