jQuery 迭代返回条件



我正在查看jQuery文档,遇到了.each函数。这本身很好,但是在他们使用的示例中,有一个我不明白的 return 语句条件。对我来说,除非"val"是"三",否则代码似乎不应该运行。然而,在评论中,它说该程序不会超过"三"。这是我不明白的部分。这是标记后跟jQuery。

<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" ];
    var obj = { one: 1, two: 2, three: 3, four: 4, five: 5 };
    jQuery.each( arr, function( i, val ) {
        $( "#" + val ).text( "Mine is " + val + "." );
        // Will stop running after "three"
        return ( val !== "three" );
    });
</script>

迭代将继续,因为函数返回true 。它在返回时停止falseval === "three"时停止。

在这里,我使用了一个简单的快速"if"而不是其他项目。

<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" ];
var obj = { one: 1, two: 2, three: 3, four: 4, five: 5 };
jQuery.each( arr, function( i, val ) {
    if (val == "three") {
        $( "#" + val ).text( "Mine is " + val + "." );
    };
});
</script>

最新更新