2012-06-22 50 views
0

我有下表。我正在嘗試使用與bg顏色匹配的tbody列bgcolors。jquery <th> bgcolor與tbody匹配

請問您能否幫忙,因爲我無法做到這一點?

感謝和問候,

<table id="one" border="1"> <thead> <tr> 
<th style="background-color:Lime">Header 1</th> 
<th>Header 2</th> </tr> </thead> <tbody> <tr> 
<td>row 1, cell 1</td> 
<td>row 1, cell 2</td> </tr> <tr> 
<td>row 2, cell 1</td> 
<td>row 2, cell 2</td> </tr> </tbody> </table> 
<script language="javascript" type="text/javascript"> 
    $(document).ready(function() { 

     $('#one thead tr th').each(function() { 

      var col1 = $(this).css("background-color"); 
      var index = $(this).closest("th").prevAll("th").length; 

      assigncolr(col1, index); 
     }); 
    }); 

    function assigncolr(col,index){ $('#one tbody tr').each(function() { 
    $(this).find('td :nth-child(' + index + ')').css("background-color", col); 


     } 
     ) 
       }; 

</script> 
+0

我要讓只有TD的匹配到其中。在上面的例子中,我想只有第一列是石灰色的謝謝, –

+0

接受的答案(顯然)解決了這個問題,但是你可以進一步簡化你的代碼,因爲'.each()'爲你提供當前的索引因此你不需要自己計算它。 (在這裏工作演示:http://jsfiddle.net/xpchG/) – nnnnnn

回答

0

一點點短,更簡單 - http://jsfiddle.net/9X4FP/1/

var cols = $("th").length; 

$("tbody td").each(function() { 
    var order = $("td").index(this) % cols; 
    var color = $("th:eq(" + order + ")").css("background-color"); 

    $(this).css("background-color", color); 
}); 
0

jQuery API: 「因爲jQuery的執行情況:第n個孩子(N)是嚴格從CSS規範衍生,n的值爲」 1索引「意思是所述計數從1開始

第二個問題是在你tdnth-child之間的空間() r選擇器。你需要消除這一點。

變化:

$(this).find('td :nth-child(' + index + ')').css("background-color", col); 

到:

$(this).find('td:nth-child(' + (index + 1) + ')').css("background-color", col); 

這應該可以解決這個問題。

工作小提琴:http://jsfiddle.net/WNscb/

+0

非常感謝。真的很有幫助。 –