Use jQuery to select multiple elements with .eq()

后端 未结 4 1983
南旧
南旧 2020-12-28 19:46

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 i

相关标签:
4条回答
  • 2020-12-28 20:28
    $('table td').filter(':eq(' + indexesToSelect.join('), :eq(') + ')')
    
    0 讨论(0)
  • 2020-12-28 20:31

    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");
    
    0 讨论(0)
  • 2020-12-28 20:33

    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]);
    
    0 讨论(0)
  • 2020-12-28 20:40

    try this

       $('table td:eq(0), table td:eq(5), table td:eq(9)')
    
    0 讨论(0)
提交回复
热议问题