2014-01-16 42 views
6

我希望循環投擲jQuery收集沒有each和回調調用。jQuery循環沒有每個和回調函數

我有下面的代碼

var found1 = false; 
$('#Root div.ListItem').each(function(index, d1) { 
    if (group == d1.text()){ found1 = true; } 
}); 

if(found1){ 
    return; 
} 

一旦found1設置爲true下一次,它始終是真實的。我想知道如何循環不each和回調像

for(var id in $('#Root div.ListItem')) { ... } 

UPDATE

我不知道如何打破循環。 我不想通過回調each

如果我在循環中傳遞jQuery對象,那麼我得到許多密鑰。

http://jsfiddle.net/LwTGU/

在該示例中有可能是一個子元素1個鍵。

回答

7

您嘗試使用for-in聲明在你的提琴實際上是遍歷所有的屬性在jQuery陣列狀物體:

for (var id in $('#Root div.ListItem')) { 
    // id is the name of the property 
} 

你不想這一點;你需要遍歷元素陣列狀物體:

for (var id in $('#root span').toArray()) { // convert to native array 
    // id is now an element found by the selector 
    $('<div />', {text: $(id).text()}).appendTo($('#out')); 
} 

You'll see in the above輸出爲您所期望的東西。

所以,回到你原來的問題。這聽起來像你只需要找到一場比賽就打破你的循環。如果你想知道如何擺脫jQuery each循環,只需在設置found1 = true;return false;。你不應該害怕傳遞迴調;該回調函數只針對您的選擇器中的每個元素在常規的舊for循環中「引擎蓋下」執行。

如果你真的想自己寫的for-each結構,那麼這樣的事情就足夠了:

var found1 = false; 
var items = $('#Root div.ListItem').toArray(); // an array of DOM elements 
for (var i = 0, j = items.length; i < j; i++) { 
    // You can access the DOM elements in the array by index, but you'll 
    // have to rewrap them in a jQuery object to be able to call .text() 
    if (group == $(items[i]).text()) { 
     found1 = true; 
     break; // no need to keep iterating once a match is found 
    } 
} 

較短,但速度慢的方式來做到這一點可能是使用$.grep並檢查是否發現任何東西:

var found1 = $.grep($('#Root div.ListItem'), function() { 
    return group == $(this).text(); 
}).length > 0; 

我不會推薦後者除非選擇器僅返回元件的少數(例如< 50)。

+0

看起來不錯 - 神奇般的,像jQuery代碼經常。但我花了一些時間搜索,我認爲這是我可以得到的最好的代碼。謝謝。 – Max

+0

@Max:我剛剛看到了編輯你的問題與小提琴的例子。我已經在我的答案中添加了一些關於您的示例的附加信息以及您的小提琴的修訂。 –

3

這聽起來像你想在遇到某些情況時停止處理。您可以通過在滿足條件時返回false做到這一點與each

var found1 = false; 
$('#Root div.ListItem').each(function(index, d1) { 
    if (group == d1.text()) { 
     found1 = true; 
     return false; 
    } 
}); 

您也可以超過$('#Root div.ListItem')的返回值重複,喜歡它的任何其他陣列(如果你堅持不使用each)。

2

因爲我沒有必要的聲望(50),所以我無法對接受的答案發表評論。不過,我不相信,預計有下面的代碼將工作:

for (var id in $('#root span').toArray()) { // convert to native array 
    // id is now an element found by the selector 
    $('<div />', {text: $(id).text()}).appendTo($('#out')); 
} 

除非我失去了一些東西,「ID」將是代表迭代數組的索引,而不是實際的數組元素的整數。如果是這樣,$(id)不會指向一個有效的jquery對象。相反,它不需要是這樣的嗎?

for (var id in $('#root span').toArray()) { // convert to native array 
    // id is now an element found by the selector 
    $('<div />', {text: $($('#root span')[id]).text()}).appendTo($('#out')); 
}