KnockoutJS table incorporating a style for alternating row colors

I use KnockoutJS in my HTML to bind data to the visibility of table rows to specific observable values, as defined in my accompanying JavaScript. My table looks like this:

<table class="myTable">
    <tr data-bind="if: thisRowVisible"> <!-- Arbitrary data here --> </tr>
    <tr data-bind="if: thatRowVisible"> <!-- Arbitrary data here --> </tr>
    <tr data-bind="if: anotherRowVisible"> <!-- Arbitrary data here --> </tr>
    <!-- More rows defined here -->
</table>

As the application starts, the table rows can be hidden or displayed using these data-bound values if. To give the table rows alternating colors (zebra / striped), in my CSS there is the following:

.myTable tr:nth-child(even) td {
   background-color: black;
}
.myTable tr:nth-child(odd) td {
   background-color: gray;
}

Typically, this CSS builds strings correctly. Even lines will be colored black, and odd lines will be gray. However, my problem arises when you enter Knockout data bindings.

, , Index # 2 . , , <tr> . . โ„–2 , , - . , .

- , KnockoutJS? - KO, <tr> Markup, CSS ?

+5
2

<!-- ko 'if': thisRowVisible -->.
: http://jsfiddle.net/zs4B2/1/.

+6

zebra . :

<table class="myTable">
    <tr data-bind="if: thisRowVisible, attr: {'class': thisRowVisible ? 'rowVisible' : 'rowInvisible' "> <!-- Arbitrary data here --> </tr>
    <tr data-bind="if: thatRowVisible, attr: {'class': thatRowVisible ? 'rowVisible' : 'rowInvisible'"> <!-- Arbitrary data here --> </tr>
    <tr data-bind="if: thatIsNotVisible, attr: {'class': thatIsNotVisible ? 'rowVisible' : 'rowInvisible'"> <!-- Arbitrary data here --> </tr>
    <!-- More rows defined here -->
</table>

CSS:

.myTable tr.rowVisible:nth-child(even) td {
   background-color: black;
}
.myTable tr.rowVisible:nth-child(odd) td {
   background-color: gray;
}

FIDDLE

+4

All Articles