javascript 使用 jQuery 通过 .eq() 选择多个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16213158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:44:28  来源:igfitidea点击:

Use jQuery to select multiple elements with .eq()

javascriptjqueryhtml-table

提问by Sean

I want to select a subset of tds from a table.

我想从表中选择 tds 的子集。

I know before hand what the indexes are, but they are effectively random (not odd or even indexes, etc).

我事先知道索引是什么,但它们实际上是随机的(不是奇数或偶数索引等)。

For instance say I want to select the 0th, 5th and 9th td.

例如说我想选择第 0、第 5 和第 9 个 td。

indexesToSelect = [0, 5, 9];

// 1) this selects the one by one
$('table td').eq(0)
$('table td').eq(5)
$('table td').eq(9)


// 2)this selects them as a group (with underscore / lodash)
var $myIndexes = $();

_.forEach(indexesToSelect, function (idx) {
    $myIndexes = $myIndexes.add($('table td').eq(idx));
});

So (2) works and I am using that, but I wonder if there is a more natural way using jQuery.

所以 (2) 有效,我正在使用它,但我想知道是否有更自然的方式使用 jQuery。

Something like passing .eq()an array of indexes? (that doesn't work)

像传递.eq()索引数组之类的东西?(这不起作用)

// does not work
$('table td').eq([0, 5, 9])

If not I will write a small plugin for something like .eqMulti(array).

如果没有,我会为类似的东西写一个小插件.eqMulti(array)

Note: there is no class that these tds share exclusively, so selecting based on class won't work.

注意:这些 td 没有专门共享的类,因此基于类进行选择将不起作用。

回答by VisioN

I'd do it with .filter()and $.inArray():

我会用.filter()和来做$.inArray()

var elements = $("table td").filter(function(i) {
    return $.inArray(i, indexesToSelect) > -1;
});

Another [more ugly] way is mapping to a selector:

另一种 [更丑陋] 的方式是映射到选择器:

var elements = $($.map(indexesToSelect, function(i) {
    return "td:eq(" + i + ")";
}).join(","), "table");

回答by Sean

I wrapped VisioN's filter method into a jQuery plugin:

我将 VisioN 的过滤器方法封装到一个 jQuery 插件中:

$.fn.eqAnyOf = function (arrayOfIndexes) {
    return this.filter(function(i) {
        return $.inArray(i, arrayOfIndexes) > -1;
    });
};

So now usage is nice and clean:

所以现在用法很好很干净:

var $tds = $('table td').eqAnyOf([1, 5, 9]);

回答by PSR

try this

试试这个

   $('table td:eq(0), table td:eq(5), table td:eq(9)')

回答by zanetu

$('table td').filter(':eq(' + indexesToSelect.join('), :eq(') + ')')