[英]Select table cells in a column based on the column header text
How can I select the cells in a column based on what text is written in the table column header, eg, "Status", using Javascript
or jQuery
? 如何根据表列标题中的文本选择列中的单元格,例如“状态”,使用Javascript
或jQuery
?
(Details, not part of the question: I want to later use this to apply background-color to the cells in that column based on the cell content, so that for example 'Error' would get the background-color red and 'Quality OK' would be white.) (细节,不是问题的一部分:我想稍后使用它根据单元格内容将背景颜色应用于该列中的单元格,以便例如“错误”将背景颜色变为红色并且'质量正常“会是白色的。”
Here is a quick fiddle i did for you.. 这是我为你做的一个快速小提琴..
http://jsfiddle.net/N2CHt/2/ http://jsfiddle.net/N2CHt/2/
HTML HTML
<table>
<tr>
<th>One</th>
<th>Two</th>
<th>Status</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>Bad</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
<td>Good</td>
</tr>
</table>
JQUERY JQUERY
$(function(){
var columnindex = $('th:contains("Status")').index();
if(columnindex != -1)
{
$('tr').each(function(){
var column = $('td', this).eq(columnindex);
switch(column.text())
{
case "Bad":
column.css({ backgroundColor: '#900' });
break;
case "Good":
column.css({ backgroundColor: '#090' });
break;
default:
break;
}
});
}
});
You can change the colours and what text you are searching for but you should be able to get a gist of whats going on... 您可以更改颜色以及要搜索的文本,但是您应该能够了解最新情况......
Basically we use the contains
selector ( https://api.jquery.com/contains-selector/ ) yp find the th
that contains the text we are looking for and then .index()
( http://api.jquery.com/index/ ) to get the columns index. 基本上,我们使用contains
选择器( https://api.jquery.com/contains-selector/ )YP找到th
包含我们正在寻找的文本,然后.index()
http://api.jquery.com / index / )获取列索引。 We then loop the tr's using .each
( https://api.jquery.com/jQuery.each/ ) and grab the item using eq
( https://api.jquery.com/eq/ ). 然后我们使用.each
( https://api.jquery.com/jQuery.each/ )循环tr,并使用eq
( https://api.jquery.com/eq/ )获取项目。 When then manipulate the css for the td
and set its background colour property. 然后操纵td
的css并设置其背景颜色属性。
One thing to note is that if 2 column th
text contain "Status" you will face problems! 有一点需要注意的是,如果2列th
文本包含“状态”,你将面对的问题!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.