簡體   English   中英

如何使用JSTL增加循環變量?

[英]How to increment a loop variable with JSTL?

我想用jstl做這樣的事情:

int i=0;
int j=0;

<c:forEach items="${commentNames}" var="comment">     

     <c:forEach items="${rates}" var="rate">

        <c:if test="${i==j}">

          int i++

        </c:if> 

     </c:forEach> 

  int j++;

</c:forEach> 

這是否可以與jstl一起使用?當我嘗試這個時它會讓我發現錯誤,我想知道是否有正確的方式來編寫它

不是直接的,但你可以使用varStatus把實例LoopTagStatus在范圍<c:forEach> 它提供了幾個getter來解決循環索引以及它是循環的第一次還是最后一次迭代。

我只是不確定你的<c:if>有意義,但我認為你實際上有兩個相同大小的列表,其中包含評論名稱和評論率,你需要只顯示與評論​​相同的索引率。

<c:forEach items="${commentNames}" var="comment" varStatus="commentLoop">     
    ${comment}
    <c:forEach items="${rates}" var="rate" varStatus="rateLoop">
        <c:if test="${commentLoop.index == rateLoop.index}">
            ${rate}
        </c:if>
    </c:forEach> 
</c:forEach> 

然而這很笨拙。 您可以直接通過索引更好地獲得費率。

<c:forEach items="${commentNames}" var="comment" varStatus="commentLoop">     
    ${comment}
    ${rates[commentLoop.index]}
</c:forEach> 

更好的是創建一個具有namerate屬性的Comment對象。

public class Comment {

    private String name;
    private Integer rate;

    // Add/autogenerate getters/setters.
}

這樣你就可以按如下方式使用它:

<c:forEach items="${comments}" var="comment">
    ${comment.name}
    ${comment.rate}
</c:forEach> 

也可以看看:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM