您尝试在小提琴中使用 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;
除非选择器只返回少数元素(例如