Max*_*Max 6 javascript jquery loops
我想循环抛出jQuery集合而没有each和回调调用.
我有以下代码
var found1 = false;
$('#Root div.ListItem').each(function( index, d1 ) {
if (group == d1.text()){ found1 = true; }
} );
if(found1){
return;
}
Run Code Online (Sandbox Code Playgroud)
一旦found1设置为真,下次总是如此.我想知道如何循环没有each和回调像
for(var id in $('#Root div.ListItem')) { ... }
Run Code Online (Sandbox Code Playgroud)
UPDATE
我不知道如何打破循环.我不希望通过回调each
如果我在循环中传递jQuery对象,那么我会得到很多键.
在该示例中,一个子元素可能有1个键.
您尝试for-in在小提琴中使用语句实际上是迭代jQuery类数组对象中的所有属性:
for (var id in $('#Root div.ListItem')) {
// id is the name of the property
}
Run Code Online (Sandbox Code Playgroud)
你不想要这个; 你需要遍历类数组对象中的元素:
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'));
}
Run Code Online (Sandbox Code Playgroud)
您将在上面看到输出是您所期望的.
所以,回到你原来的问题.听起来你只需要在找到匹配后突破你的循环.如果您想知道如何打破jQuery each循环,只需return false;在设置之后found1 = true;.你不应该害怕传递回调; 该回调仅针对选择器中的每个元素在常规的旧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
}
}
Run Code Online (Sandbox Code Playgroud)
更短但更慢的方法可能是使用$.grep并检查它是否找到了任何东西:
var found1 = $.grep($('#Root div.ListItem'), function() {
return group == $(this).text();
}).length > 0;
Run Code Online (Sandbox Code Playgroud)
除非选择器只返回少数元素(例如<50),否则我不会推荐后者.
| 归档时间: |
|
| 查看次数: |
3426 次 |
| 最近记录: |