2012-03-02 95 views
1

問題:如果特定文本位於標題td中,則需要更改整列的背景顏色。我嘗試了幾種不同的方式,但沒有運氣。根據標題文本更改列的背景顏色

我試圖獲取標頭:

$('td:contains(Sun)').addClass('.weekend');

這並不工作,甚至改變顏色。那就是我目前被卡住的地方。

+1

保健佳品你試過嗎? – 2012-03-02 22:15:11

+0

只是證明標題td文本是否等於特定文本。然後根據需要更改背景顏色。你的概率究竟在哪裏? – 2012-03-02 22:17:59

+0

我不明白你的問題。 – joakimdahlstrom 2012-03-02 22:21:39

回答

3

Fiddle

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'); 
    }); 
} 
-1

你可以使用table col。您應該根據服務器端標題的值更改樣式屬性。

jsfiddle

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

此方法需要您設置在服務器端的山坳。

0

因爲你沒有提供很多細節,所以我不得不提供你想要的東西,但是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'); 
});​ 

這將需要更新,以評估所選日的文本,但也許這是足以讓你開始

0

類似下面會做的伎倆,

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

我的代碼在這裏:

<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> 
相關問題