如何使用JQuery将表头颜色应用于表体

时间:2013-07-26 08:27:35

标签: javascript jquery css asp.net-mvc

我正在研究ASP.NET MVC应用程序。它具有使用Table显示月度数据的功能。它根据季度显示,因此它是动态创建的。每个月显示为 周-1周-2周-3周-3周那样。这个名字显示在表格标题部分 对于每个月我显示为不同颜色的背景我已经实现了这些东西。现在它以颜色显示表头。我的问题是如何将这种背景颜色应用于表tds?它应该以coloumnwise显示。我将使用JQuery。
例如:
如果coloumn标题为红色,则每列td应为背景颜色相同。

编辑:这是jsfiddle.net/ucfs8/ 我试图插入jsfiddle显示错误,请转到jsfiddle的链接

编辑编辑:解决方案是没有任何方法可以使用CSS只是因为JQuery在浏览应用程序时很慢。实际上这是基于树结构。单击节点然后向下钻取到子节点。一个节点有大约10个子节点。然后花时间使用JQuery加载。感谢。

3 个答案:

答案 0 :(得分:3)

如果您能够找到感兴趣的列,那么它应该很容易:

$(document).ready(function() {
     var color = $("table>thead th").css("background-color")
     $("table>tbody td").css("background-color", color)
}

您可以使用数字子选择器选择每个列,例如:

for(...length){
   var color = $("table>thead th:nth-child(1)").css("background-color");
   $("table>tbody td:nth-child(1)").css("background-color", color)
}

答案 1 :(得分:1)

点击此处,更新演示http://jsfiddle.net/yeyene/ucfs8/2/

$(document).ready(function () {
    var col = $('table tr td');
    $('table tbody tr').each(function () {
        $(this).css('background-color','whitesmoke');
        for (var i = 0; i <= col.length; i++) {
            var color = $('table th').eq(i).css('background-color');
            $(this).find('td').eq(i).css('background-color', color);
        }
    });
});

答案 2 :(得分:1)

如果您自己生成表格,只需添加一个col组并设置样式。

像(jsFiddle example):

<colgroup>
        <col style="width: 3%; background-color: whitesmoke" />
        <col style="width: 10%; background-color: whitesmoke" />
        <col style="width: 11%; background-color: whitesmoke" />
        <col style="background-color:#ebcccc" />
        <col style="background-color:#ebcccc" />
        <col style="background-color:#ebcccc" />
        <col style="background-color:#ebcccc" />
        <col style="background-color:#dff0d8" />
        <col style="background-color:#dff0d8" />
        <col style="background-color:#dff0d8" />
        <col style="background-color:#dff0d8" />
        <col style="background-color:#dff0d8" />
        <col style="background-color:#d9edf7" />
        <col style="background-color:#d9edf7" />
        <col style="background-color:#d9edf7" />
        <col style="background-color:#d9edf7" />
        <col style="background-color:#d0e9c6" />
        <col style="background-color:#d0e9c6" />
        <col style="background-color:#d0e9c6" />
        <col style="background-color:#d0e9c6" />
        <col style="background-color:#d0e9c6" />
        <col/>
</colgroup>

理想情况下,你会使用一些css类:D