如何将 css 应用于表行



我需要将背景颜色应用于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");
});

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

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

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

现场演示

<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");
});

请注意,jQuery选择器就像CSS选择器一样licList:tr:odd所以它不是一个有效的选择器。不过,您可以仅使用CSS来执行此操作:

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

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

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

CSS3 允许这样做,不要去 javascript,因为你很容易做到

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

演示

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

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

小提琴

最新更新