我有这段代码:
var image_match = $('#my_id image').filter(function(i, el) {
return el.attributes.x.value == x_image;
});
$('#my_id image')
给出了一个非常长的数组(数千)但幸运的是我知道有多少元素会通过测试(通常只有一个)所以我可以在找到元素时立即停止'循环'(s )。问题是我不知道该怎么做(或者如果可能的话)。
这是为了提高效率,所以我正在寻找一种有效的解决方案。
也许这样的事情,但它有效吗?
var target_number=3;//or whatever
var image_match = $('#my_id image').filter(function(i, el) {
var counter=0;
if (el.attributes.x.value == x_image) {
counter+=1;
};
if (counter==target_number) {
return el.attributes.x.value == x_image;
break;//return (false);//exit
}
return el.attributes.x.value == x_image;
});
答案 0 :(得分:4)
你不能打破filter()
循环,因为它的设计是将逻辑应用于所有元素。
如果您想提前退出循环,我建议您更改逻辑以使用each()
。然后你可以return false;
退出循环:
var target_number = 3, matches = [];
$('#my_id image').each(function(i, el) {
if (el.attributes.x.value == x) {
matches.push($(this));
if (matches.length == target_number)
return false;
}
});
matches
现在大致相当于image_match
变量的内容,除了它将是一个数组而不是jQuery对象。