-1

我可以实现 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.
});
4

3 回答 3

3

return false这样做:

var elem;

$( "li" ).each(function() {
    if($(this).text() == 'foo') {
        elem = this;
        return false;
    }
});
于 2013-03-30T07:37:26.223 回答
2

从文档。

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

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

于 2013-03-30T07:37:48.513 回答
1

jQuery 文档

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

Example:

<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>`
于 2013-03-30T07:45:18.780 回答