Dragon Dragon - 6 months ago 27
CSS Question

how to change background color in html by using jquery

I have a table that odd lines in table have a origin

background-color
because of class
table-striped
.

I am willing add double click action for a table in html.
background-color
of a line(
tr
) should be changed if double click on it. It seems I can't override the
background-color
when I double click on odd lines. What's wrong with my code? Is there another way to override the background by using
jquery
?

Here are my code:

CSS style

.selected-hight {
background-color: #FECA40;
}
.table-striped tbody>tr:nth-child(odd)>td, .table-striped tbody>tr:nth-child(odd)>th {
background-color: #0e90d2;
}





and JQuery method.

$(function() {
$("table tbody").on("dblclick",'tr', function() {
var rows = $('table tbody tr');
rows.removeClass('selected-hight');
$(this).addClass('selected-hight');
});
});





and html code of table:

<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>

Answer

Yes you can override. Try to add a new class to avoid adding !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>