如何使用 jQuery 选择表格列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8375625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to select a table column with jQuery
提问by
I want to select a table column and all I know is the header text of the column. (th.innerText)
我想选择一个表格列,我只知道该列的标题文本。(th.innerText)
I tried the following code but it doesn't work:
我尝试了以下代码,但不起作用:
ownerIndex = $('th:contains("Owner")').index();
$('table tr td:nth-child(ownerIndex)')
any ideas?
有任何想法吗?
回答by
Ok. I found a solution:
好的。我找到了一个解决方案:
$('table tr td:nth-child('+ownerIndex+')')
回答by Tristan
In the example above ownerIndex needs to be incremented by 1 to match the indexing of nth-child, which starts at 1 rather than 0.
在上面的例子中,ownerIndex 需要增加 1 以匹配第 n 个子节点的索引,它从 1 开始而不是 0。
Here's my take: http://jsfiddle.net/2xU8t/
这是我的看法: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");
回答by illibrarian
This seems to work using the back tick as opposed to a single quote:
这似乎使用反勾号而不是单引号起作用:
$(`table tr td:nth-child(${ownerIndex})`)