我需要檢索列表中每個值的索引位置。我這樣做,以便我可以顯示交替行背景顏色的gsp表。例如:Groovy/Grails - 需要檢索列表索引值
(list.indexVal % 2) == 1 ? 'odd' : 'even'
如何獲取Groovy列表中每個項目的索引位置編號?謝謝!
我需要檢索列表中每個值的索引位置。我這樣做,以便我可以顯示交替行背景顏色的gsp表。例如:Groovy/Grails - 需要檢索列表索引值
(list.indexVal % 2) == 1 ? 'odd' : 'even'
如何獲取Groovy列表中每個項目的索引位置編號?謝謝!
According the documentation中,G:在GSP視圖中的每個標籤允許 「狀態」 變量 其中的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] %>
...
<% } %>
這工作,萬分感謝! – grantmcconnaughey
此回覆非常有用,因爲它指出中的「狀態」功能的存在 –