简体   繁体   中英

Use jQuery to select multiple elements with .eq()

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'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]);

试试这个

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM