javascript - 如何使用 jquery 更改 html 中的背景颜色

标签 javascript jquery html css

我有一个表格,表格中的奇数行有一个原点 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/

相关文章:

javascript - 通过缩小和 require.js 进行 MVC 捆绑

javascript - 使用Jquery/AJAX在JSP页面中通过linux绝对路径显示文本文件内容

javascript - JavascriptMVC Controller 事件处理程序中的自定义选择?

javascript - 使用 jquery 测试事件序列

c# - 无法将列表保存到 session /ViewBag 变量

html - 为什么我的列表样式图像在不同浏览器中的位置不同

javascript - 有条件地启用禁用下拉列表和文本字段

html - 显示 : inline-block DIV pushed downward

javascript - 在浏览 HTML 页面时保持音频播放器持续/连续播放

javascript - 当文件名位于 redux 存储中时如何指定图像路径