You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ng-repeat实现表格斑马纹效果的问题求助

搞定AngularJS表格斑马纹的问题!

嘿,我来帮你捋清楚问题出在哪,以及怎么解决:

问题核心:表格结构错了!

你把ng-repeat绑定在了<tbody>标签上,这会导致每一条数据都生成一个独立的<tbody>容器,每个容器里只有一行<tr>。这种情况下,不管是用Angular的$even/$odd还是CSS的奇偶选择器,都没法正确识别行的奇偶性——毕竟每个<tbody>里的<tr>都是第一个子元素啊!

另外你还固定给<tr>加了class="clr",没有根据奇偶动态切换类名,这自然出不来斑马纹效果。

解决方案:两种方法任你选

方法1:用AngularJS的ng-class结合$even/$odd

首先修正结构,把ng-repeat移到<tr>上,整个表格只保留一个<tbody>:

<thead class="rowhead">
  <tr>
    <th class="mid">Sl.</th>
    <th id="tnm">Name</th>
    <th class="mid">Age</th>
    <th class="mid">Members</th>
    <th class="mid">View-content</th>
    <th class="mid">on-going-Process</th>
  </tr>
</thead>
<tbody>
  <!-- 把ng-repeat移到tr上,用ng-class动态绑定类名 -->
  <tr ng-repeat="info in cspinfo" ng-class="{ 'even-row': $even, 'odd-row': $odd }">
    <td>{{$index+1}}</td>
    <td id="bnm">{{info.name}}</td>
    <td>{{info.age}}</td>
    <td>{{info.member}}</td>
    <td>{{info.View-content}}</td>
    <td>{{info.on-going-Process}}</td> <!-- 这里你之前漏了info.,要补上才能渲染数据 -->
  </tr>
</tbody>

然后添加对应的CSS样式:

.even-row {
  background-color: #f8f9fa; /* 自定义偶数行颜色 */
}
.odd-row {
  background-color: #ffffff; /* 自定义奇数行颜色 */
}

方法2:纯CSS实现(更简洁)

如果结构正确(所有行在同一个<tbody>下),直接用CSS的:nth-child()选择器就能搞定,不用改Angular指令:

<thead class="rowhead">
  <tr>
    <th class="mid">Sl.</th>
    <th id="tnm">Name</th>
    <th class="mid">Age</th>
    <th class="mid">Members</th>
    <th class="mid">View-content</th>
    <th class="mid">on-going-Process</th>
  </tr>
</thead>
<tbody>
  <tr ng-repeat="info in cspinfo" class="clr">
    <td>{{$index+1}}</td>
    <td id="bnm">{{info.name}}</td>
    <td>{{info.age}}</td>
    <td>{{info.member}}</td>
    <td>{{info.View-content}}</td>
    <td>{{info.on-going-Process}}</td>
  </tr>
</tbody>

对应的CSS:

tbody tr:nth-child(even) {
  background-color: #f8f9fa;
}
tbody tr:nth-child(odd) {
  background-color: #ffffff;
}

额外小提醒

你之前的<td>{{on-going-Process}}</td>少了info.前缀,这样没法正确渲染数据,我在上面的代码里已经帮你修正啦~

内容的提问来源于stack exchange,提问作者SRK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:15:34