如何更改表格行的背景?

时间:2017-02-05 09:01:24

标签: jquery html css

我的HTML代码:

<table class="tableclass">
<th>id</th><th>Name</th><th>Value</th>
<tr>
    <td>001</td>
    <td>Name 001</td>
    <td>This is some value for Key 001</td>
</tr>

<tr>
    <td>002</td>
    <td>Name 002</td>
    <td>This is some value for Key 002</td>
</tr>

<tr>
    <td>003</td>
    <td>Name 003</td>
    <td>This is some value for Key 003</td>
</tr>

<tr>
    <td>004</td>
    <td>Name 004</td>
    <td>This is some value for Key 004</td>
</tr>

</table>

我能用CSS显示替代颜色:

tr:nth-child(even) {
    background-color: #CCD1D1;
}

我的jQuery突出显示点击的表格行:

$(".tableclass tr").click(function(){
    $(this).addClass("rowHighlight");
});

班级.rowHighlight{background-color:#AEB6BF;}

使用此代码我无法更改具有css背景的奇数行的背景颜色。我希望能够改变那些行的背景。

我该怎么做?

感谢。

3 个答案:

答案 0 :(得分:1)

只需使用.rowHighlight td {background-color:你的颜色;

$(".tableclass tr").click(function(){
    $(this).addClass("rowHighlight");
});
table {
border:0px solid #CCC;
border-collapse:collapse;
}
td {
    border:none;
}
tr:nth-child(even) {
    background-color: #CCD1D1;
}




.rowHighlight td{background-color:red; padding:0px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table class="tableclass">
<th>id</th><th>Name</th><th>Value</th>
<tr>
    <td>001</td>
    <td>Name 001</td>
    <td>This is some value for Key 001</td>
</tr>

<tr>
    <td>002</td>
    <td>Name 002</td>
    <td>This is some value for Key 002</td>
</tr>

<tr>
    <td>003</td>
    <td>Name 003</td>
    <td>This is some value for Key 003</td>
</tr>

<tr>
    <td>004</td>
    <td>Name 004</td>
    <td>This is some value for Key 004</td>
</tr>

</table>

答案 1 :(得分:1)

在jQuery中,改为执行此操作

$(".tableclass tr").click(function(){
    $(this).css("background-color","#AEB6BF")
});

答案 2 :(得分:1)

<table class="tableclass">
<th>id</th><th>Name</th><th>Value</th>
<tr>
    <td>001</td>
    <td>Name 001</td>
    <td>This is some value for Key 001</td>
</tr>

<tr>
    <td>002</td>
    <td>Name 002</td>
    <td>This is some value for Key 002</td>
</tr>

<tr>
    <td>003</td>
    <td>Name 003</td>
    <td>This is some value for Key 003</td>
</tr>

<tr>
    <td>004</td>
    <td>Name 004</td>
    <td>This is some value for Key 004</td>
</tr>

</table>

**If you want to change the row color on hover or on click, you can do this using css.** 

.tableclass tr:hover, .tableclass tr:active, .tableclass tr:visited{
background-color: #CCD1D1;
cursor:pointer;

}