【问题标题】:Groovy/Grails - Need to retrieve List index valueGroovy/Grails - 需要检索列表索引值
【发布时间】:2013-02-07 19:53:56
【问题描述】:

我需要检索我拥有的列表中每个值的索引位置。我这样做是为了显示一个具有交替行背景颜色的 gsp 表。例如:

(list.indexVal % 2) == 1 ? 'odd' : 'even'

如何获取 Groovy 列表中每个项目的索引位置编号?谢谢!

【问题讨论】:

    标签: list grails groovy indexing


    【解决方案1】:

    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>
    

    【讨论】:

    • 此响应非常有帮助,因为它指出了 中存在“状态”功能
    【解决方案2】:

    可以使用g:eacheachWithIndexfor 中的任何一个循环。

    但是,对于这种特定情况,不需要索引值。推荐使用 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] %>
       ...
    <% } %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-03
      • 1970-01-01
      • 1970-01-01
      • 2015-06-18
      • 2020-10-12
      • 2014-04-07
      • 2018-12-14
      相关资源
      最近更新 更多