Pergunta

I have a table which is zebra-striped:

tr:nth-child(even)
{
    background-color: red;
}
tr:nth-child(odd)
{
    background-color: blue;
}

I want to show/hide its rows, keeping the table striped (recolored from a changed row to the last one). I see 2 ways to do this:

  1. Create an invisible table and move <TR>s with jQuery after() to/from it. I've tested detaching and it works (the table is being recolored on detaching), but inserting the detached (to nowhere) rows doesn't, so moving rows to another table should help, I guess.
  2. Call jQuery toggle() along with creating/removing invisible <TR> right after the one we are toggling.

Which one is better? Maybe, there is even a better way?

Regards,

Foi útil?

Solução

CSS's :nth-child selector selects an element based on its index among its siblings. It does not take the visibility (or other selectors) of an element into account.

Instead of adding/removing rows using jQuery, just add/remove class names: http://jsfiddle.net/rTER4/

var $allRows = $('tr:visible');
var $oddRows = $allRows.filter(':odd');
var $evenRows = $allRows.filter(':even');

// Remove old classes, then add new ones.
$oddRows.removeClass('even').addClass('odd');
$evenRows.removeClass('odd').addClass('even');

/* CSS */
tr.even { background-color: red; }
tr.odd  { background-color: blue;}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top