我有一个表格,表格中的奇数行有一个原点 background-color
因为 table-striped
类。
我愿意为 html 中的表格添加双击操作。如果双击一行 (tr
) 的 background-color
应该改变它。当我双击奇数行时,我似乎无法覆盖 background-color
。我的代码有什么问题?有没有另一种方法可以使用 jquery
覆盖背景?
这是我的代码:
CSS 样式
.selected-hight {
background-color: #FECA40;
}
.table-striped tbody>tr:nth-child(odd)>td, .table-striped tbody>tr:nth-child(odd)>th {
background-color: #0e90d2;
}
和 JQuery 方法。
$(function() {
$("table tbody").on("dblclick",'tr', function() {
var rows = $('table tbody tr');
rows.removeClass('selected-hight');
$(this).addClass('selected-hight');
});
});
以及表格的html代码:
<table class="table-striped">
<thead>
<tr>
<td>head 1</td>
<td>head 2</td>
</tr>
<thead>
<tbody>
<tr>
<td>row 0, col 0</td>
<td>row 0, col 1</td>
</tr>
<tr>
<td>row 1, col 0</td>
<td>row 0, col 1</td>
</tr>
<tbody>
</table>
最佳答案
是的,你可以覆盖。尝试添加一个新类以避免添加 !important
$(function() {
$("table tbody").on("dblclick",'tr', function() {
var rows = $('table tbody tr');
rows.removeClass('selected-hight');
$(this).addClass('selected-hight');
});
});
.table-striped tbody>tr:nth-child(odd)>td, .table-striped tbody>tr:nth-child(odd)>th {
background-color: #0e90d2;
}
.table-striped tbody > tr.selected-hight > td, .table-striped tbody > tr.selected-hight > th{
background-color: #FECA40;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table class="table-striped">
<thead>
<tr>
<td>head 1</td>
<td>head 2</td>
</tr>
<thead>
<tbody>
<tr>
<td>row 0, col 0</td>
<td>row 0, col 1</td>
</tr>
<tr>
<td>row 1, col 0</td>
<td>row 0, col 1</td>
</tr>
<tbody>
</table>
关于javascript - 如何使用 jquery 更改 html 中的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37319307/