2011-12-20 60 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; 
});