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)); });
这是基于这个例子:
head1 head2 head3 cell1a cell2a cell3a cell1b cell2b cell3b cell1c cell2c cell3c
您应该使用:eq(index)filter。
在确定了要选择的列的索引(让我们称之为idx
)之后,您可以执行以下操作:
$('#yourTableID tr').each(function(){ // for each row: var myField = $(this).children('td:eq('+idx+')'); // do stuff with the selected field });