简体   繁体   中英

How to highlight a table row upon hover conditionally based on table cell values with CSS and jQuery?

So I have an HTML table populated with negative and positive values. I want to query the specific values and then upon hovering over the table values less than 0 I want to highlight the row with a red background color and for values greater than or equal to 0 should highlight with a blue background.

My current attempt is:

$(document).ready(function(){
    var rows = $("#htmlTable").find('tbody').find('tr');
    $.each(rows, function(key, value){
        var rowData = $(rows[key]).find('td:eq(1)').html();
        if (rowData < 0) {
            $("tr").hover(function(){
                $(this).addClass('.table-style-1 tbody > tr:hover');
            }
        }
        else {
            $("tr").hover(function(){
                $(this).addClass('.table-style-2 tbody > tr:hover');
            });
        }
    });
});

The CSS classes are as follows:

.table-style-1 tbody > tr:hover {
    background-color: red;
}

.table-style-2 tbody > tr:hover {
    background-color: blue;
}

My above code is correctly getting the data from the table as can been seen with a simple console.log(rowData) line so I am assuming that my problem is with my implementation of addClass() and hover() functions. The console isn't showing any syntax errors but the table has no highlight functionality upon hovering. Any help would be greatly appreciated.

Since you're getting a string with rowData = $(rows[key]).find('td:eq(1)').html(); you shoud cast the value into an integer when you do a comparison, eg

if (parseInt(rowData, 10) < 0) { ...

Also why exactly are you adding a class like .table-style-2 tbody > tr:hover ? You should just add the a class to the rows eg negative or positive (note: you need to use $(this) and not $('tr') )

if (parseInt(rowData, 10) < 0) {
    $(this).addClass('negative');
}
else {
    $(this).addClass('positive');
}

and define your css like so

tr.negative:hover {
    background-color: red;
}

tr.positive:hover {
    background-color: blue;
}

here is an example: http://jsfiddle.net/wgkf4o9j/

$(document).ready(function(){
    $('table').on('mouseover','tr',function(event){
        var $tr = $(event.currentTarget);
        $tr.parents('table').find('td').removeClass('blue red');
        var value = parseInt($tr.find('td:eq(1)').html());      
        $tr.find('td').addClass(value < 0?'red':'blue');
    })
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM