簡體   English   中英

使用jQuery選擇.eq()的多個元素

[英]Use jQuery to select multiple elements with .eq()

我想從表中選擇tds的子集。

我事先知道索引是什么,但它們實際上是隨機的(不是奇數或偶數索引等)。

例如,我想選擇第0,第5和第9個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));
});

所以(2)工作,我正在使用它,但我想知道是否有一種更自然的方式使用jQuery。

像傳遞.eq()索引數組的東西? (那不起作用)

// does not work
$('table td').eq([0, 5, 9])

如果不是,我會為.eqMulti(array)類的東西編寫一個小插件。

注意:這些tds沒有專門共享的類,因此基於類的選擇將不起作用。

我用.filter()$.inArray()

var elements = $("table td").filter(function(i) {
    return $.inArray(i, indexesToSelect) > -1;
});

另一種[ 更難看的 ]方式是映射到選擇器:

var elements = $($.map(indexesToSelect, function(i) {
    return "td:eq(" + i + ")";
}).join(","), "table");

我將VisioN的過濾方法包裝到jQuery插件中:

$.fn.eqAnyOf = function (arrayOfIndexes) {
    return this.filter(function(i) {
        return $.inArray(i, arrayOfIndexes) > -1;
    });
};

所以現在用法很干凈:

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(') + ')')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM