jQuery .filter():在结束前退出

时间:2017-07-26 15:12:38

标签: javascript jquery filter

我有这段代码:

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;
});

1 个答案:

答案 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对象。