我有下表。我正在嘗試使用與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>
我要讓只有TD的匹配到其中。在上面的例子中,我想只有第一列是石灰色的謝謝, –
接受的答案(顯然)解決了這個問題,但是你可以進一步簡化你的代碼,因爲'.each()'爲你提供當前的索引因此你不需要自己計算它。 (在這裏工作演示:http://jsfiddle.net/xpchG/) – nnnnnn