使用 jQuery 通过 .eq() 选择多个元素 [英] Use jQuery to select multiple elements with .eq()

查看:22
本文介绍了使用 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).

注意:这些 td 没有专门共享的类,因此无法根据类进行选择.

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");

这篇关于使用 jQuery 通过 .eq() 选择多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆