【问题标题】:return in jQuery.each [duplicate]在 jQuery.each 中返回 [重复]
【发布时间】:2013-03-30 07:35:16
【问题描述】:

我可以实现 jQuery.each,其中如果我在 jQuery.each 中处理的数组中找到任何匹配项,那么我可以中断/返回而无需进一步处理剩余元素。

<ul>
<li>foo</li>
<li>bar</li>

您可以选择列表项并遍历它们:

$( "li" ).each(function( index ) {
  //if($(this).text() == 'foo') , i.e if foo is found , 
//then return instead of processing bar.
});

【问题讨论】:

  • 当你有这样的问题时,你应该考虑阅读the documentation:“我们可以通过让回调函数返回 false 来打破 $.each() 循环在特定的迭代。返回非-false 与 for 循环中的 continue 语句相同;它将立即跳到下一次迭代。"

标签: jquery


【解决方案1】:

return false 这样做:

var elem;

$( "li" ).each(function() {
    if($(this).text() == 'foo') {
        elem = this;
        return false;
    }
});

【讨论】:

  • 很好,简短的解释。返回 false 表示 break,返回 true 表示 continue
【解决方案2】:

来自文档。

我们可以通过让回调函数返回 false 来在特定的迭代中打破 $.each() 循环。返回非 false 与 for 循环中的 continue 语句相同;它会立即跳到下一次迭代

http://api.jquery.com/jQuery.each/

【讨论】:

    【解决方案3】:

    来自jQuery documentation

    我们可以在特定的迭代中打破 $.each() 循环,方法是 回调函数返回假。返回非 false 与 a 相同 for 循环中的 continue 语句;它会立即跳到下一个 迭代。

    示例:

    <div id="one"></div>
    <div id="two"></div>
    <div id="three"></div>
    <div id="four"></div>
    <div id="five"></div>
    
    <script>
    
        var arr = [ "one", "two", "three", "four", "five" ];
        jQuery.each(arr, function() {
            $("#" + this).text("Mine is " + this + ".");
            return (this != "three"); // will stop running after "three"
        });
    
    </script>`
    

    【讨论】:

      猜你喜欢
      • 2011-04-18
      • 2013-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-22
      • 2015-04-30
      相关资源
      最近更新 更多