[英]jquery: Change the background-colour of a column if its header has a class
I have the following jQuery that I'm trying to use to change the background colour of a column where its header has a class. 我尝试使用以下jQuery来更改其标题具有类的列的背景颜色。
So for example: 因此,例如:
$('th').each(function (i) {
if ($(this).hasClass('headerSortUp') || $(this).hasClass('headerSortDown')) {
sortIndex = $(this).index();
}
$('tr').each(function () {
$('td:eq(' + sortIndex + ')').css('background-color', 'orange');
});
});
So if I had a table like: 因此,如果我有一个像这样的表:
<table>
<tr>
<th class="headerSortDown">Header</th>
<th>Header</th>
<th>Header</th>
<th>Header</th>
<th>Header</th>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
</table>
So in this example the whole first column should have a bg of orange. 因此,在此示例中,整个第一列应包含bg橙色。 However it's not working... Any ideas what I have done wrong?
但是它不起作用...任何想法我做错了吗? Thanks
谢谢
您忘记指定上下文
$('td:eq(' + sortIndex + ')', this).css('background-color', 'orange');
Try changing sortIndex = $(this).index();
尝试更改
sortIndex = $(this).index();
to sortIndex =i;
to
sortIndex =i;
and 和
$('td:eq(' + sortIndex + ')').css('background-color', 'orange');
to 至
$('td:eq(' + sortIndex + ')',$(this)).css('background-color', 'orange');
to select td 's withing the tr 选择与t一起的td
There's no need to iterate over the <th>
elements - a selector can pick out just the ones with the right classes. 无需遍历
<th>
元素-选择器可以仅选择具有正确类的元素。
You can then use .index()
to find their column value, and :nth-child()
to select every <td>
in that column in one go: 然后,您可以使用
.index()
查找其列值,并使用:nth-child()
一次性选择该列中的每个<td>
:
$('.headerSortUp, .headerSortDown').each(function() {
var n = $(this).index() + 1;
$('td:nth-child(' + n + ')').css('background-color', 'orange');
});
Working demo at http://jsfiddle.net/jNsF4/ http://jsfiddle.net/jNsF4/上的工作演示
[I note also that the original code has a logic error - the code to change the colours should be inside the if { ... }
block, not outside it]. [我还注意到,原始代码有逻辑错误-更改颜色的代码应在
if { ... }
块内,而不是在其外部]。
There's probably a better selector that causes lesser iterations 可能有更好的选择器,可以减少迭代次数
var sortIndex;
$('th').each(function (i) {
if ($(this).hasClass('headerSortUp') || $(this).hasClass('headerSortDown')) {
sortIndex = $(this).index();
}
});
$('td:nth-child(' +sortIndex+1+')').css('background-color', 'orange');
You can check the fiddle here http://jsfiddle.net/ryan_s/nZr9G/ 您可以在这里查看小提琴http://jsfiddle.net/ryan_s/nZr9G/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.