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

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

如果不是,我会写一个像<$的小插件c $ c> .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");

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

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