[英]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.