2009-11-18 61 views

回答

1

您应该使用:eq(index)过滤器。

已经确定要选择的列的索引后(我们称之为idx),你可以这样做:

$('#yourTableID tr').each(function(){ 
    // for each row: 
    var myField = $(this).children('td:eq('+idx+')'); 
    // do stuff with the selected field 
}); 
+0

这只是TD的一次一个选择。循环对于一张大桌子来说可能很大。 – 2009-11-19 01:49:14

+0

同意,不是解决方案。非常低效的方式去做。 – redsquare 2010-05-13 05:17:37

6

要获得第一列:

$(function() { 
    var col = $("td:nth-child(1)"); 
}); 
+0

我喜欢jQuery的清洁。很好的答案。 – 2009-11-19 01:47:32

2

最直接的将是获得该行中头的位置(索引),然后访问相同列索引处的所有单元的值。

$('#table th').click(function() { 
    var th = $(this); 
    var index = $('th', th.parents('tr')).index(th); 
    var column = $('tbody td:nth-child(' + (index + 1) + ')', th.parents('table')); 
    var values = column.map(function() { 
     return $(this).text(); 
    }); 
    alert($.makeArray(values)); 
}); 

这是基于这个例子:

<table id="table"> 
    <thead> 
     <tr><th>head1</th><th>head2</th><th>head3</th></tr> 
    </thead> 
    <tbody> 
     <tr><td>cell1a</td><td>cell2a</td><td>cell3a</td></tr> 
     <tr><td>cell1b</td><td>cell2b</td><td>cell3b</td></tr> 
     <tr><td>cell1c</td><td>cell2c</td><td>cell3c</td></tr> 
    </tbody> 
</table>