2010-10-15 14 views
2

如何在滿足條件時突破以下jquery的每種方法;

var rainbow = {'first' : 'red', 'second' : 'orange', 'third' : 'yellow'}; 

$.each(rainbow, function (key, color) { 

    if (color == 'red') { 

    //do something and then break out of the each method 
    alert("i'm read, now break."); 

    } 

}); 
+2

我認爲這是一個 「回報」。 – ericteubert 2010-10-15 16:19:38

+0

可能重複的[如何擺脫JQuery的每個循環](http://stackoverflow.com/questions/1784780/how-to-break-out-of-jquerys-each-loop) – outis 2012-03-28 04:57:29

回答

2

由於明確寫入jQuery的頁面上$.each

我們可以通過使 回調函數返回打破在 特定迭代$。每()循環假。 返回非錯誤與for循環中的 continue語句相同;它 將立即跳轉到下一個 迭代。

請在此處發佈之前,請先谷歌搜索條件!可惜的是,如果你不花時間閱讀它,jQuery將擁有最好的文檔之一!

+0

謝謝,我沒有做你在我發佈之前建議的。我有閱讀障礙,所以有時候我會錯過文本,即使它正好在我面前。 – dkinzer 2010-10-15 16:29:26

+0

@DKinzer:對不起,如果我的評論聽起來暴力或粗魯: - / – tsimbalar 2010-10-15 16:40:22

3
var rainbow = {'first' : 'red', 'second' : 'orange', 'third' : 'yellow'}; 

$.each(rainbow, function (key, color) { 

    if (color == 'red') { 

    //do something and then break out of the each method 
    alert("i'm read, now break."); 

    return false; 

    } 

}); 
1

JQuery documentation for each狀態:

我們可以通過將回調函數返回false打破在一個特定的迭代。每個$()循環。返回非錯誤與for循環中的continue語句相同;它會立即跳到下一個迭代。

它也提供了例子。

1
<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> 

試試這個

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

1

我們不能用break和continue在jQuery函數
試試這個

var rainbow = {'first' : 'red', 'second' : 'orange', 'third' : 'yellow'}; 

$.each(rainbow, function (key, color) { 

    if (color == 'red') { 
    //do something and then break out of the each method 
    alert("i'm read, now break."); 
    return false; 
    } 
    alert(color); 
});