doutan2111 2013-04-25 11:09
浏览 1544
已采纳

使用jQuery选择.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.

  • 写回答

4条回答 默认 最新

  • duan1227 2013-04-25 11:11
    关注

    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");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?