Setting the background colour back to original after jquery changes it
Basically I have a table with many rows. The Table alternates between white and grey backgrounds using some css
.profile tr:nth-child(odd) { background:#eee; }
.profile tr:nth-child(even) { background:none; }
Now I want the user to be able to select a row and it highlights into yellow. Done with some simple Jquery
$(".Select").click(function() {
//Deselect all other Rows
$(".Select").show().prev().hide().parent().parent().css('background', 'none');
//get Id
var Row = $(this).parent().parent();
var MatchId = Row.attr('id');
$(this).hide().prev().show();
Row.css('background', '#FFFFBA');
});
Problem is where i grab all rows with the $(".select").......parent().parent().css('background....
setting it to "none" makes all the rows white and loses the alterna开发者_运维技巧tive colouring is there a way to return the background property to its original state.
create a third class:
.profile tr.hover { background:#FFFFBA; }
instead of
Row.css('background', '#FFFFBA');
you do
Row.addClass("hover");
and instead of
$(".Select").s.//.parent().css('background', 'none');
you do
$(".Select").s.//.parent().removeClass("hover");
the // is just to shorten the long line.
Instead of all that trouble, just use the CSS selector for the TR in your .css stylesheet and use the :hover
markup and let the browser handle it. Any job you can offload to the underlying browser you should.
However, I'm not entirely sure from your code that that's what you're wanting to do. It looks like you want to change the background of some other row than the one you're on. If that's the case then you'll need to attach a bit of .data()
to the target object and use a mouse out event to change it back from whatever you stored.
$(".Select").show().prev().hide().parent().parent().css('background', '');
Caspar is correct here, for a few reasons:
- You keep your presentation in the CSS
- Browsers apply CSS faster than manipulating the style object in JavaScript
- If you add additional styles to the highlighted item (such as a border, bold text, etc.) there's no performance hit (see reason 2).
Having said that, if you want to just keep the code you have, simply remove the odd rows from your jQuery selector using the $.not()
selector:
$(".Select").show().prev().hide().parent().parent().not(':nth-child(odd)').css('background', 'none');
精彩评论