jQuery:如何仅根据表头从表的列中选择值

我有一个带标题ID的表。 我需要选择此标题下的所有字段。 我无权访问源代码,并且此表中没有使用任何类。 有关如何完成这项工作的任何想法?

要获得第一列:

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

最简单的方法是获取行中标题的位置(索引),然后访问同一列索引处所有单元格的值。

 $('#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)); }); 

这是基于这个例子:

 
head1head2head3
cell1acell2acell3a
cell1bcell2bcell3b
cell1ccell2ccell3c

您应该使用:eq(index)filter。

在确定了要选择的列的索引(让我们称之为idx )之后,您可以执行以下操作:

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