[英]jquery: Change the background-colour of a column if its header has a class
我尝试使用以下jQuery来更改其标题具有类的列的背景颜色。
因此,例如:
$('th').each(function (i) {
if ($(this).hasClass('headerSortUp') || $(this).hasClass('headerSortDown')) {
sortIndex = $(this).index();
}
$('tr').each(function () {
$('td:eq(' + sortIndex + ')').css('background-color', 'orange');
});
});
因此,如果我有一个像这样的表:
<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>
因此,在此示例中,整个第一列应包含bg橙色。 但是它不起作用...任何想法我做错了吗? 谢谢
您忘记指定上下文
$('td:eq(' + sortIndex + ')', this).css('background-color', 'orange');
尝试更改sortIndex = $(this).index();
to sortIndex =i;
和
$('td:eq(' + sortIndex + ')').css('background-color', 'orange');
至
$('td:eq(' + sortIndex + ')',$(this)).css('background-color', 'orange');
选择与t一起的td
无需遍历<th>
元素-选择器可以仅选择具有正确类的元素。
然后,您可以使用.index()
查找其列值,并使用:nth-child()
一次性选择该列中的每个<td>
:
$('.headerSortUp, .headerSortDown').each(function() {
var n = $(this).index() + 1;
$('td:nth-child(' + n + ')').css('background-color', 'orange');
});
http://jsfiddle.net/jNsF4/上的工作演示
[我还注意到,原始代码有逻辑错误-更改颜色的代码应在if { ... }
块内,而不是在其外部]。
可能有更好的选择器,可以减少迭代次数
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');
您可以在这里查看小提琴http://jsfiddle.net/ryan_s/nZr9G/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.