KnockoutJS表格中加入交替行颜色的样式

5

我在HTML中使用KnockoutJS将表格行的可见性与特定的可观察值数据绑定,这些值在我附带的JavaScript中定义。我的表格如下所示:

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

应用程序运行时,可以使用这些数据绑定的if值来隐藏或显示表格的行。为了给表格的行设置交替颜色(斑马线/条纹),我在我的CSS中定义了以下内容:

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

通常,这个 CSS 可以正确地为行设置样式,偶数行是黑色的,奇数行是灰色的。但是当使用 Knockout data-bindings 时会出现问题。
例如,假设索引为 #2 的行因为数据绑定被隐藏了。即使该行被隐藏,该行的 <tr> 定义仍然存在于表中。这会打乱交替行颜色。由于索引 #2 仍然存在但是被隐藏了,因此它仍然包含在交替行颜色中。这意味着两个灰色的行会重叠在一起。
在使用 KnockoutJS 模式的同时实现正确的交替表行颜色有什么方法吗?是否有一些 KO 数据绑定的技巧可以从标记中完全删除隐藏的 <tr>,以便正确应用 CSS 样式?

虚拟元素怎么样:<!-- ko 'if': thisRowVisible --><tr> <!-- 在此处添加任意数据 --> </tr><!-- /ko --> - Vladimir
2个回答

6

哇,+1,我不知道那个,太棒了!! - Jalayn
1
问题在于如果绑定在“讨论主题”版本中tr内部的所有内容都没有渲染,但空的tr标签仍然存在。如果我们使用虚拟元素,那么tr将完全消失,css将按预期工作。 - Vladimir
谢谢,这个有效。虚拟元素防止了在不应该可见时显示<tr> - Patrick D

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

FIDDLE EXAMPLE


虽然我接受了 Vladamir 的答案,但我也非常喜欢这个解决方案。它将所有的数据绑定都保持在单一的 data-bind 标签中。我标记 Vladamir 的原因仅仅是因为使用这个解决方案时,对于每个绑定,我需要两次引用绑定的 thisRowVisible 变量,一次是用于 if,另一次是用于 attr。如果使用虚拟绑定,我只需要引用一次。除此之外,我确实喜欢这个答案。谢谢。 - Patrick D
@PatrickD,我也更喜欢Vladimir的解决方案,它很优雅:) - Artyom Neustroev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接