【问题标题】:jQuery .filter(): exit before the endjQuery .filter():在结束前退出
【发布时间】:2017-07-26 15:12:37
【问题描述】:

我有这个代码:

var image_match = $('#my_id image').filter(function(i, el) {
    return  el.attributes.x.value == x_image;
});

$('#my_id image') 给出了一个很长的数组(几千个),但幸运的是我知道有多少元素会通过测试(通常只有一个),所以我可以在找到元素后立即停止“循环”。问题是我不知道该怎么做(或者如果可能的话)。

这是为了提高效率,所以我正在寻找一个有效的解决方案。

也许是这样,但它有效吗?

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

【问题讨论】:

标签: javascript jquery filter


【解决方案1】:

您无法跳出 @9​​87654321@ 循环,因为它旨在将其逻辑应用于所有元素。

如果您想提前退出循环,我建议您更改逻辑以使用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 对象。

您也可以使用map() 直接构建一个仅包含所需值的数组:

let matches = $('#my_id image').map((i, el) => el.attributes.x.value === x ? $(el) : null).get();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-10
    • 1970-01-01
    • 2016-04-30
    • 2016-10-11
    • 2015-07-20
    相关资源
    最近更新 更多