如何使用jQuery选择表列

时间:2011-12-04 13:28:59

标签: jquery html-table jquery-selectors

我想选择一个表格列,我所知道的只是列的标题文本。 (th.innerText)

我尝试了以下代码,但它不起作用:

ownerIndex = $('th:contains("Owner")').index();
$('table tr td:nth-child(ownerIndex)')

任何想法?

3 个答案:

答案 0 :(得分:53)

确定。我找到了解决方案:

$('table tr td:nth-child('+ownerIndex+')')

答案 1 :(得分:22)

在上面的示例中,ownerIndex需要递增1以匹配nth-child的索引,该索引从1开始而不是0。

这是我的看法: http://jsfiddle.net/2xU8t/

/* Set all the cells in columns with THEHEADING in the heading to red */

// Find the heading with the text THEHEADING
columnTh = $("table th:contains('THEHEADING')");

// Get the index & increment by 1 to match nth-child indexing
columnIndex = columnTh.index() + 1; 

// Set all the elements with that index in a tr red
$('table tr td:nth-child(' + columnIndex + ')').css("color", "#F00");

// Set the heading red too!
columnTh.css("color", "#F00"); 

答案 2 :(得分:2)

这似乎与后面的勾号相反,而不是单引号:

$(`table tr td:nth-child(${ownerIndex})`)
相关问题