使用jQuery选择.eq()的多个元素
我想从表格中选择一个tds子集。
I want to select a subset of tds from a table.
我事先知道索引是什么,但它们实际上是随机的(不是奇数或偶数索引)等等。)
I know before hand what the indexes are, but they are effectively random (not odd or even indexes, etc).
比如说我想选择第0,第5和第9个td。
For instance say I want to select the 0th, 5th and 9th 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));
});
所以(2)有效,我正在使用它,但我想知道是否有更自然的方式使用jQuery。
So (2) works and I am using that, but I wonder if there is a more natural way using jQuery.
像传递 .eq()
一系列索引? (这不起作用)
Something like passing .eq()
an array of indexes? (that doesn't work)
// does not work
$('table td').eq([0, 5, 9])
如果不是,我会写一个像 .eqMulti(array)。
If not I will write a small plugin for something like .eqMulti(array)
.
注意:没有这些tds专属的类,所以选择基于类获胜工作。
Note: there is no class that these tds share exclusively, so selecting based on class won't work.
我用 .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");