[英]Use jQuery to select multiple elements with .eq()
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? 像传递
.eq()
索引数组的东西? (that doesn't work) (那不起作用)
// 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. 注意:这些tds没有专门共享的类,因此基于类的选择将不起作用。
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");
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]);
试试这个
$('table td:eq(0), table td:eq(5), table td:eq(9)')
$('table td').filter(':eq(' + indexesToSelect.join('), :eq(') + ')')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.