首页 > 解决方案 > 使用 jQuery 查找元素的多个索引(索引)

问题描述

我正在使用一个遗留的 jQuery 项目,需要获取具有类的表的所有列的索引unsortedjQuery 可以轻松获取单个索引,但我需要获取索引数组。我怎样才能做到这一点?

例如,即使unsorted该类有多个列,这也将返回一个整数:

$('.some-table th').index($('th.unsorted'))

其他问题

虽然这个问题提到了 jQuery,但它确实与 jQuery 或 DOM 元素无关,因此对我没有帮助。

标签: jquery

解决方案


由于 jQuery 没有该功能,它可能是

const $ths = $('.some-table th');
let indices = $.map($('th.unsorted'), function(element) {
  return $ths.index(element);
});

或者您可以自己扩展该功能。

jQuery.fn.extend({
  indices: function(selector) {
    return $.map($(selector), function(element) {
      return this.index(element);
    });
  },
});

let indices = $('.some-table th').indices('th.unsorted');

此外,出于性能原因,您可以自己编写搜索逻辑。


推荐阅读