【问题标题】:loop is not breaking when return statement used使用 return 语句时循环没有中断
【发布时间】:2015-06-01 04:24:08
【问题描述】:

我试图根据某些条件返回一个对象,即如果满足某些条件,我想打破循环并将对象返回给被调用的函数。

下面是我的代码。

function someFun(that,filterID,columnSelctedID) {
    $.each(that.filters,function(i,filter) {
        if(filter.id==filterID) {
            $.each(filter.filters,function(j,column) {
                if(column.id==$('#' + columnSelctedID + ' .rule-filter-container-column select').val()) {
                    return column;
                }
            });
        }
    });
}

【问题讨论】:

  • 你确定 if ever 运行吗?
  • 如果您能在小提琴中重现该问题,那将非常有帮助。
  • if(filter.id==filterID),filter.id在哪里你会得到价值?
  • @nicael 是的,我可以看到控件位于return column 行并继续循环。
  • @WahyuKodar 在 $.each 中你可以找到具有 id 属性的名称过滤器的对象

标签: javascript jquery


【解决方案1】:

您必须使用return false 来打破.each 循环。您可以使用外部变量来分配选定的值。这样的事情可能会奏效

function someFun(that,filterID,columnSelctedID) {
    var col; // this is used to hold selected column
    $.each(that.filters,function(i,filter) {
        if(filter.id==filterID) {
            $.each(filter.filters,function(j,column) {
                if(column.id==$('#' + columnSelctedID + ' .rule-filter-container-column select').val()) {
                    col = column;
                    return false;
                }
            });
        }
    });
    return col;
}

【讨论】:

  • 但是我想将列返回给被调用的函数,当然我可以使用全局变量但我不感兴趣
  • @user1655222:刚刚将 return col 添加到函数中。您可能想在外部每个上添加一些条件以使其也中断。也许检查何时更改其默认值?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-26
  • 2011-08-17
  • 2014-08-28
  • 2011-05-10
  • 2018-06-16
相关资源
最近更新 更多