我正在处理一个旧的 jQuery 项目,需要获取具有类 unsorted
的表的所有列的索引。 jQuery can easily get a single index, 但我需要得到一个索引数组。我该怎么做?
例如,即使有多个具有 unsorted
类的列,这也将返回一个整数:
$('.some-table th').index($('th.unsorted'))
虽然 this question 提到了 jQuery,但它确实与 jQuery 或 DOM 元素无关,因此对我没有帮助。
答案 0 :(得分:1)
因为 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');
此外,出于性能原因,您可以自己编写搜索逻辑。
答案 1 :(得分:0)
如果您所有的 th.unsorted
都是兄弟姐妹(都在同一个 thead
中),那么您不需要 collection.index(selector)
并且可以将 .map()
应用到 {{1} } 直接列出。
如果它们(例如)在不同的行上,则使用其他答案中的 th.unsorted
。
collection.index(element)
console.log($("table th.unsorted").map((i, e) => $(e).index()).toArray())