如何将css应用于表行

时间:2013-01-28 07:44:34

标签: c# jquery asp.net html

我需要将背景颜色应用于我的html表的交替行。

我目前的代码:

.licList
    {
        width: 100%;
        border: 1px solid #f7f7f7;
        text-align: center;
        border-collapse: collapse;
    }

    .licList th
    {
        font-weight: bold;
        background-color: #dbdbdb;
        border-bottom: 1px solid #f1f1f1;
        padding: 4px 5px;
    }

    .licList td
    {
        padding: 4px 5px;
    }

    .odd
    {
        background-color: #ffffff;
    }
    .odd td
    {
        border-bottom: 1px solid #cef;
    }

和jquery是

    $(document).ready(function () {
        $("licList:tr:odd").addClass("odd");
    });

我确定上面的jquery不正确我在单页中有多个表,所以我无法应用

$(document).ready(function(){
    $("tr:odd").addClass("odd");
});

所以我的问题是如何解决这个问题????

5 个答案:

答案 0 :(得分:3)

  

jquery不正确我在单页中有多个表,所以我不能   应用

为您的表分配id/class并访问该表下的行。假设你的表有id tbl

<强> Live Demo

<table id="tbl">
   <tr>
        <td>1</td>
        <td>1</td>
   </tr> 
   <tr>
        <td>1</td>
        <td>1</td>
   </tr> 
</table>

$(document).ready(function(){
    $("#tbl tr:odd").addClass("odd");
});

答案 1 :(得分:3)

请记住,jQuery选择器就像CSS选择器一样,因此licList:tr:odd不是有效的选择器。你可以用CSS做到这一点:

.licList:nth-child(odd) { ... }

答案 2 :(得分:2)

偶数行和奇数行都有一个Jquery选择器。您可以将其与表ID一起使用,

$(document).ready(function(){
    $("#table1 tr:odd").addClass("odd");
    $("#table1 tr:even").addClass("even");
});

答案 3 :(得分:2)

CSS3允许这样做,不要使用javascript,因为你可以很容易地做到这一点

tr:nth-child(odd)    { background-color:#eee; }
tr:nth-child(even)    { background-color:#fff; }

DEMO

答案 4 :(得分:1)

如果您使用jQuery.each(),那么它将是table的两个集合,您可以从那里过滤而不是大量的tr

$('table').each(function(){
    $(this).find('tr').filter(':odd').addClass("odd"); //first rows always the same
});

fiddle