根据标题文本更改列的背景颜色
问题描述:
问题:如果特定文本位于标题td
中,则需要更改整列的背景颜色。我尝试了几种不同的方式,但没有运气。根据标题文本更改列的背景颜色
我试图获取标头:
$('td:contains(Sun)').addClass('.weekend');
这并不工作,甚至改变颜色。那就是我目前被卡住的地方。
答
var txt = 'Header 2';
var column = $('table tr th').filter(function() {
return $(this).text() === txt;
}).index();
if(column > -1) {
$('table tr').each(function() {
$(this).find('td').eq(column).css('background-color', '#eee');
});
}
答
你可以使用table col。您应该根据服务器端标题的值更改样式属性。
<table>
<colgroup>
<col />
<col />
<col />
<col style="background-color:red" />
<col />
<col />
</colgroup>
<thead>
<tr>
<th>Head 1</th>
<th>Head 2</th>
<th>Head 3</th>
<th>Head 4</th>
<th>Head 5</th>
<th>Head 6</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1</td>
<td>Row 2</td>
<td>Row 3</td>
<td>Row 4</td>
<td>Row 5</td>
<td>Row 6</td>
</tr>
<tr>
<td>Row 1</td>
<td>Row 2</td>
<td>Row 3</td>
<td>Row 4</td>
<td>Row 5</td>
<td>Row 6</td>
</tr>
</tbody>
</table>
此方法需要您设置在服务器端的山坳。
答
因为你没有提供很多细节,所以我不得不提供你想要的东西,但是here's a quick demo我放在了jsFiddle上。它的要点是:
.selected {
background-color: #ddd;
}
$('table th').click(function() {
var index = parseInt($(this).index(), 10) + 1;
$('.selected').removeClass('selected');
$('table tbody tr :nth-child(' + index + ')').addClass('selected');
});
这将需要更新,以评估所选日的文本,但也许这是足以让你开始
答
类似下面会做的伎俩,
JS:
$('document').ready(function() {
$('table thead th').click(function() {
var colIndex = $(this).index();
$('table tbody tr').each(function() {
$(this).find('td').each(function(i) {
if (i == colIndex) {
$(this).addClass('selCol');
} else {
$(this).removeClass('selCol');
}
});
});
});
});
CSS:
.selCol { background-color: #c2c2c2; }
答
我的代码在这里:
<html>
<head>
<title></title>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("table thead th").each(function(i,e){
if($(e).text() == "Column2"){
var ind = i + 1;
$(e).css("background-color", "red")
$('table tbody tr :nth-child(' + ind + ')').css("background-color", "red");
}
});
});
</script>
<head>
<body>
<table>
<thead>
<tr>
<th>Column1</th>
<th>Column2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Apple Inc</td>
<td>AAPL</td>
</tr>
<tr>
<td>GoogleInc</td>
<td>GOOG</td>
</tr>
</tbody>
</table>
</body>
</html>
保健佳品你试过吗? – 2012-03-02 22:15:11
只是证明标题td文本是否等于特定文本。然后根据需要更改背景颜色。你的概率究竟在哪里? – 2012-03-02 22:17:59
我不明白你的问题。 – joakimdahlstrom 2012-03-02 22:21:39