根据标题文本更改列的背景颜色

问题:如果特定文本位于标题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'); }); } 

由于你没有提供很多细节,我不得不展示你正在尝试的东西,但这里是我在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'); });​ 

这将需要更新以评估所选th的文本,但也许它足以让你开始

像下面的东西可以做到这一点,

DEMO

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; } 

我的代码在这里:

        
Column1 Column2
Apple Inc AAPL
GoogleInc GOOG

你可以使用表格col 。 您应该根据服务器端标头的值更改样式属性。

的jsfiddle

 
Head 1 Head 2 Head 3 Head 4 Head 5 Head 6
Row 1 Row 2 Row 3 Row 4 Row 5 Row 6
Row 1 Row 2 Row 3 Row 4 Row 5 Row 6

此方法需要您在服务器端设置col。