5

I'm using KnockoutJS in my HTML to data-bind the visibility of rows of a table to certain 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 runs, the rows of the table may be hidden or shown, by using these data-bound if values. In order to give the rows of the table alternating colors (zebra/striping), I have the following defined in my CSS:

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

Normally, this CSS would style the rows properly. The even rows would be colored black, and the odd rows would be colored gray. However, my problem occurs when you throw in the Knockout data-bindings.

For instance, let's say the Index #2 row is hidden, as a result of my data-binding. Even though the row is hidden, my <tr> definition for that row still exists in the table. This throws off the alternating row colors. Since Index #2 still exists, but is hidden, it is still included in the alternating row colors. This means that two gray rows will appear on top of each other.

Is there any to achieve the proper alternating table row colors, while still using my KnockoutJS pattern? Is there some trick to the KO data-binding to remove the hidden <tr> from Markup completely, so that the CSS styles are applied correctly?

4

2 回答 2

6

您可以使用虚拟元素<!-- ko 'if': thisRowVisible -->
工作示例:http: //jsfiddle.net/zs4B2/1/

于 2013-04-29T14:09:15.210 回答
4

您可以仅将特定类分配给可见元素并仅为该类应用斑马样式。数据绑定如下:

<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;
}

小提琴示例

于 2013-04-29T14:06:59.777 回答