[英]Alternative row coloring in html table with ng-repeat
我有一个表,其中使用ng-repeat填充值。 我需要用绿色和黄色为表格的行上色。 我没有ng-repeat尝试了以下方法,它可以工作。
.table-striped>tbody>tr:nth-of-type(odd) { background: yellow !important; } .table-striped>tbody>tr:nth-of-type(even) { background: green !important; }
<html> <div><table class="table table-striped"> <thead style="border: 1px solid"> <tr> <th>Heading</th> </tr> </thead> <tbody> <tr> <td>{{value.val1}}</td> </tr> <tr> <td>{{value.val2}}</td> </tr> <tr> <td>{{value.val3}}</td> </tr> </tbody> </table> </div> <html>
但是在按以下方式使用ng-repeat时它不起作用(所有行本身都是黄色)。 请帮助。谢谢。
.table-striped>tbody>tr:nth-of-type(odd) { background: yellow !important; } .table-striped>tbody>tr:nth-of-type(even) { background: green !important; }
<html> <div><table class="table table-striped"> <thead style="border: 1px solid"> <tr> <th>Heading</th> </tr> </thead> <tbody ng-repeat="value in values"> <tr> <td>{{value.val1}}</td> </tr> </tbody> </table> </div> <html>
我认为您应该将ng-repeat =“ value in values”赋予tr而不是tbody。 您对身体的重复会重复身体元素。
您可以使用指令ng-class-odd =“'classname'”。
<html>
<div>
<table class="table table-striped">
<thead style="border: 1px solid">
<tr>
<th>Heading</th>
</tr>
</thead>
<tbody ng-repeat="value in values">
<tr class="row-color" ng-class-odd="'odd'">
<td>{{value.val1}}</td>
</tr>
<tr class="row-color" ng-class-odd="'odd'">
<td>{{value.val2}}</td>
</tr>
<tr class="row-color" ng-class-odd="'odd'">
<td>{{value.val3}}</td>
</tr>
</tbody>
</table>
</div>
<html>
然后在您的CSS中,您可以执行以下操作
.row-color {
background: green;
}
.row-color.odd {
background: yellow;
}
这也摆脱了您的!important,这通常被认为是不好的做法。
您可以将类动态添加到行中,然后指定所需的样式。
<tr class="myrow">
$(".myrow:odd").addClass("odditem");
$(".myrow:even").addClass("evenitem");
虽然我认为OP的解决方案是将ng-repeat
从<tbody>
移到<tr>
,因为它匹配了他的预期结构而没有ng-repeat
; 当ng-repeat
位于<tbody>
层上时,完全可以单独使用css进行着色。
tbody:nth-of-type(odd)>tr { background-color: pink; } tbody:nth-of-type(even)>tr { background-color: purple; }
<table> <tbody> <tr><td>row1</td></tr> </tbody> <tbody> <tr><td>row2</td></tr> </tbody> <tbody> <tr><td>row3</td></tr> </tbody> </table>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.