quick JQuery question, I've got a products page that the user can filter. Each time a filter is applied/removed, a change event calls stripeTable()
. I tried to implement the table striping using the following function, however after removing an item and calling stripTable(), the striping did not remain consistent, i.e each visible odd row one colour, each visible even row another.
function stripeTable() {
// Find all odd visible table rows and add .odd class.
$("#resultsTable > tbody > tr:even:visible").each(function() {
$(this).addClass('even');
});
// Find all even visible table rows and add .even class.
$("#resultsTable > tbody > tr:odd:visible").each(function() {
$(this).addClass('odd');
});
}
I cannot work out why the above wouldn't work. I managed to implement the function as below and it works fine. Any ideas?
function stripeTable() {
var count = 1;
// get all visible table rows
$("#resultsTable > tbody > tr").each(function () {
// If table row is visible, strip accordingly.
// Row 0 (table headers) not striped.
if ($(this).is(":visible") && (this.rowIndex !== 0)) {
if ((count % 2) != 0) {
// Remove class .even if applied previously
$(this).removeClass("even");
// Odd row, add class .odd
$(this).addClass("odd");
count++;
} else {
// Remove class .odd if applied previously
$(this).removeClass("odd");
// Even row, add class .even
$(this).addClass("even");
count++;
}
}
});
}
For clarity, stripeTable()
is the last function called, the table rows are hidden/shown in the table before hand. Thanks.