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

使用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条)

报告相同问题?

悬赏问题

  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺