开发者

Highlight first column in a row using JQuery

I have a table, as I hover over the cells within the table the current cell and the first column is highlighted:

$('.price_cell').hover(function(){

    $(this).css('background-color','#cce6ff');
    $('td:first', $(this).parents('tr')).css({'background-color':'#0096E1','color':'#ffffff'});

},
function(){

    $(this).css('background-color','#ffffff');
    $('td:first', $(this).parents('tr')).css({'background-color':'#ffffff','color':'#002436'});
});

This works fine. However whilst I want the first column cells to change color as a user hovers over the cells on the line, I don't开发者_Go百科 want the first column cells to change color when they are hovered over.


You can also do this with pure css.

table tr:hover                 { background-color: black; color:white;}
table tr:hover td:first-child  { background-color:white; color:black }

example : http://jsfiddle.net/wBu5M/


Check the index of the hovered cell, and change the CSS if the hovered cell isn't the first in the row:

$('.price_cell').hover(
    function() {
        if ($(this).index() != 0) {
            ...
        }
    },
    function() {
        if ($(this).index() != 0) {
            ...
        }
    }
);        

or, potentially more efficient since it'll create a single pair of callbacks instead of registering a pair on every cell:

$('table')
    .delegate('.price_cell', 'mouseenter', function() {
        if ($(this).index() != 0) {
            // hover-in style here
        }
    })
    .delegate('.price_cell', 'mouseleave', function() {
        if ($(this).index() != 0) {
            // hover-out style here
        }
    });

NB: I'm not using :not(:first-child) here since that requires more work parsing the selector than the trivial $(this).index() call.


Change your selector to:

$('.price_cell:not(:first-child)').hover(function(){

Using the delegate suggestion from Phrogz:

$('#mytable').delegate('.price_cell:not(:first-child)', 'mouseenter', function() {
    $(this).css('background-color','#cce6ff');
    $('td:first', $(this).parents('tr')).css({'background-color':'#0096E1','color':'#ffffff'});

}).delegate('.price_cell:not(:first-child)', 'mouseleave', function() {
    $(this).css('background-color','#ffffff');
    $('td:first', $(this).parents('tr')).css({'background-color':'#ffffff','color':'#002436'});
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜