on doc.ready, I've done $("tr:even").css("background-color","orange");
. I then have a button that does the following: $("#tr3).remove()
which removes the 3rd tr (I id'ed the third tr "tr3"). I then apply the orange bgcolor to even rows AGAIN in order to update the tr bgcolors now that the table has 1 less tr, but the tr bgcolor's don't refresh. I end up with 2 orange tr's in a row, instead of having every other tr be orange background. make sense?
views:
129answers:
4try applying also on the odd one:
$("tr:odd").css("background-color","your color");
$("tr:even").css("background-color","orange");
as I think it is because when you remove the 3rd tr, all tr next to it changes. the odd becomes even and the even becomes odd.
It would be easier if you made that background color a css class:
.odd { background-color: orange; }
Then in javascript:
$(function() {
$("tr:even").addClass("odd");
$("#button").click(function() {
$("#tr3").remove();
$("tr").removeClass("odd").filter(":nth-child(odd)").addClass("odd");
});
});
You can use this to access the nth element:
$("tr:nth-child(3n)") //will match with 3rd, 6th, ...
you can change 3n
or do simple add and substract to it:
$("tr:nth-child(3n+1)") //will match with 1st, 4th, 7th, ...
$("tr:nth-child(3n+2)") //will match with 2nd, 5th, 8th, ...
:nth
can be used in filter too, for example:
$(SELECTOR).filter(":nth-child(3n)")
I hope this is what you looking for.
UPDATE:
After re-read your question, I thing I got it wrong.
In my code, I put the code in separated function:
function zebra_table($) {
$("tr").removeClass("odd");
$("tr:odd").addClass("odd");
}
Then after I change the table's row, such as delete one of it, or add new row, I will simply call the function above:
jQuery(function($){
//after DOM loaded, apply zebra
zebra_table($);
//...
//after modify table
zebra_table($);
});
The key is, make the table 'plain' again, then re-apply the zebra rules in the current table structure.
All, thanks so much for your help!!! I ended up doing the following:
$(document).ready(function() {
$("tr:odd").addClass("odd");
$("#button").click(function () {
$("#tr3").remove();
$("tr").removeClass("odd");
$("tr:odd").addClass("odd"); // re-add class to odd tr's
});
});
and that worked! Didn't need to do any filter(n) stuff. Thanks again for the help!!!