【发布时间】:2013-02-07 19:53:56
【问题描述】:
我需要检索我拥有的列表中每个值的索引位置。我这样做是为了显示一个具有交替行背景颜色的 gsp 表。例如:
(list.indexVal % 2) == 1 ? 'odd' : 'even'
如何获取 Groovy 列表中每个项目的索引位置编号?谢谢!
【问题讨论】:
标签: list grails groovy indexing
我需要检索我拥有的列表中每个值的索引位置。我这样做是为了显示一个具有交替行背景颜色的 gsp 表。例如:
(list.indexVal % 2) == 1 ? 'odd' : 'even'
如何获取 Groovy 列表中每个项目的索引位置编号?谢谢!
【问题讨论】:
标签: list grails groovy indexing
According the documentation,gsp 视图中的 g:each 标签允许“status”变量 grails 将迭代索引存储在其中。 示例:
<tbody>
<g:each status="i" in="${itemList}" var="item">
<!-- Alternate CSS classes for the rows. -->
<tr class="${ (i % 2) == 0 ? 'a' : 'b'}">
<td>${item.id?.encodeAsHTML()}</td>
<td>${item.parentId?.encodeAsHTML()}</td>
<td>${item.type?.encodeAsHTML()}</td>
<td>${item.status?.encodeAsHTML()}</td>
</tr>
</g:each>
</tbody>
【讨论】:
可以使用g:each、eachWithIndex 或for 中的任何一个循环。
但是,对于这种特定情况,不需要索引值。推荐使用 css 伪类:
tr:nth-child(odd) { background: #f7f7f7; }
tr:nth-child(even) { background: #ffffff; }
如果还需要获取索引,选项有:
<g:each status="i" in="${items}" var="item">
...
</g:each>
<% items.eachWithIndex { item, i -> %>
...
<% } %>
<% for (int i = 0; i < items.size(); i++) { %>
<% def item = items[i] %>
...
<% } %>
【讨论】: