您嘗試使用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)。
看起來不錯 - 神奇般的,像jQuery代碼經常。但我花了一些時間搜索,我認爲這是我可以得到的最好的代碼。謝謝。 – Max
@Max:我剛剛看到了編輯你的問題與小提琴的例子。我已經在我的答案中添加了一些關於您的示例的附加信息以及您的小提琴的修訂。 –