【问题标题】:Splitting an Arraylist in a table using a Foreach Loop in JSP在 JSP 中使用 Foreach 循环拆分表中的 Arraylist
【发布时间】:2015-06-17 11:41:08
【问题描述】:

这里有一个问题,我在如下所示的 jsp 页面中的 foreach 循环中有一个 arrayList。所以,我想有 3 列,每列有 3 行,每列都有连续的值。我应该如何以最简单的方式应用此场景?

澄清一下:

Column1      Column2      Column3
 Data1        Data4        Data7
 Data2        Data5        Data8
 Data3        Data6        Data9


<table>
<c:set var="numCols" value="3"/>
<c:forEach items="${dataList}" var="info" varStatus = "status"> 
   <c:if test="${status.index % numCols == 0}">
    <tr>
    </c:if>
        <td><input type ="submit" class="data btnColor" 
                   value="${info.dataName}" label ="${info.dataId}" />
        </td>
        <c:if test="${status.count % numCols == 0 or status.last}">
    </tr>
    </c:if>
</c:forEach>

【问题讨论】:

  • 有人在吗?请帮忙!
  • 您需要更新您尝试运行的代码。您上面的代码没有改变。在我看到您尝试运行的内容之前,我无法帮助您了解为什么它没有运行。
  • @Shaggy125 请帮我解决这个问题,如何设置行中 3 的限制?
  • 很抱歉让您失望了希望您能理解
  • @Shaggy125 先生,您能写出每一行重要代码的用途以用于文档目的吗?

标签: jsp arraylist foreach jstl jsp-tags


【解决方案1】:

您快到了,但我不确定您对代码示例中的输入做了什么。要使表格仅显示 3 列,您可以使用 varStatus 标记循环运算符。文档说明了与之相关的方法。

<c:set var="numCols" value="3"/>
<c:set var="numRows" value="3"/>
<c:set var="rowCount" value="0"/>
<table>
    <tr>
        // Loop through each element in the dataList and assign it to a variable named info
        <c:forEach items="${dataList}" var="info" varStatus="status"> 
            // If the current row count is less than the number of row allowed, proceed
            <c:if test="${rowCount lt numRows}">
                // Output the element (info) into a table cell
                <td><input type ="submit" class="data btnColor" value="${info.dataName}" label ="${info.dataId}" /></td>
                // Check to see if the cell that was just created is the 3 one in the row,
                // excluding the very first cell of the table (because 0 % 0 is undefined)
                <c:if test="${status.count ne 0 && status.count % numCols == 0}">
                    // Increment the row count
                    <c:set var="rowCount" value="${rowCount + 1}"/>
                    // End that row and start a new one
                    </tr><tr>
                </c:if>
            </c:if>
        </c:forEach>
    </tr>
</table>

查看these examples 了解有关 c:foreach 标签的更多信息。

【讨论】:

  • 实际上,arraylist 是一系列按钮,这就是为什么有一个输入类型按钮具有其特定值和标签的原因。我认为您提供的代码不符合我的需求,我已经知道该怎么做。但我正在寻找的是,foreach 循环中的一个条件,它将在第一列中仅列出 3 行,并在下一列中继续其余的行。
  • 刚刚修改了我的答案以包含 varStatus。
  • varStatus 将让您知道您正在进行的循环迭代,从 0(基于 0 的索引)开始。所以我要说的是,如果索引 mod 3 的余数等于 0,则打印出行的结尾 和下一行的开头 。我也将修改我的答案,因为我刚刚意识到我遗漏了第一次迭代的检查。
  • 这回答了你的问题吗?
  • 另外,先生,我怎样才能为每列设置 3 行?使用 有必要吗?请帮忙。
猜你喜欢
相关资源
最近更新 更多
热门标签