最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Use jQuery to select multiple elements with .eq() - Stack Overflow

programmeradmin0浏览0评论

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).

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

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

Something like passing .eq() an array of indexes? (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).

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

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).

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

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

Something like passing .eq() an array of indexes? (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).

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

Share Improve this question edited Aug 26, 2018 at 16:57 Brian Tompsett - 汤莱恩 5,88372 gold badges61 silver badges133 bronze badges asked Apr 25, 2013 at 11:09 SeanSean 16k5 gold badges39 silver badges37 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 16

I'd do it with .filter() and $.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:

$.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]);

try this

   $('table td:eq(0), table td:eq(5), table td:eq(9)')
$('table td').filter(':eq(' + indexesToSelect.join('), :eq(') + ')')
发布评论

评论列表(0)

  1. 暂无评论