2011-12-20 39 views
3

我有一個索引數組(無特定順序),我需要根據這些索引在表中選擇所有<tr>獲取基於行索引數組的jQuery集合

我有什麼感覺馬虎&效率低下。有沒有更好的方法來編寫這個選擇器?

對於那些誰喜歡擺弄:http://jsfiddle.net/PwnhJ/1/

對於其他人:

<table> 
    <tr> 
     <td>one</td> 
    </tr> 
    <tr> 
     <td>two</td> 
    </tr> 
    <tr> 
     <td>three</td> 
    </tr> 
    <tr> 
     <td>four</td> 
    </tr> 
    <tr> 
     <td>five</td> 
    </tr> 
    <tr> 
     <td>six</td> 
    </tr> 
    <tr> 
     <td>seven</td> 
    </tr> 
</table> 

var indices = [0,3,4,6]; 
//What I'd love to do 
alert($("tr").eq(indices).length); //returns 0 

//What does work, but feels sloppy & inefficient 
var selector = ""; 
$(indices).each(function(i, index){ 
    selector += "tr:eq(" + index + ")"; 
    if(i + 1 != indices.length){ 
     selector += "," 
    } 
}); 

alert($(selector).length); //returns 4 

任何幫助,意見,建議,將不勝感激。

謝謝!

回答

6

http://jsfiddle.net/aUmNK/1/

var indices = [0,3,4,6]; 

console.log(jQuery("table tr").filter(function(){ 
    return jQuery.inArray(this.rowIndex, indices) > -1; 
})); 
+0

好極了!我知道必須有更好的方法。非常感謝! – 2011-12-20 15:15:25

1

試試這個

var indices = [0,3,4,6]; 

$("table > tr").filter(function(index){ 
    return $.inArray(index, indices) > -1; 
});