如何从jstl中的foreach循环获取索引值

时间:2013-09-16 10:36:22

标签: java jsp for-loop foreach jstl

我在request对象中设置了值,如下所示,

String[] categoriesList=null;
categoriesList = engine.getCategoryNamesArray();
request.setAttribute("categoriesList", categoriesList );

这就是我在jsp页面中迭代的方式

<% if(request.getAttribute("categoriesList") != null) { %>
<c:forEach var="categoryName" items="${categoriesList}">
   <li><a onclick="getCategoryIndex()" href="#">${categoryName}</a></li>
</c:forEach>
<% }%>

如何获取每个元素的索引并将其传递给JavaScript函数onclick="getCategoryIndex()"

5 个答案:

答案 0 :(得分:204)

使用varStatus获取索引c:forEach varStatus properties

<c:forEach var="categoryName" items="${categoriesList}" varStatus="loop">
    <li><a onclick="getCategoryIndex(${loop.index})" href="#">${categoryName}</a></li>
</c:forEach>

答案 1 :(得分:15)

我面临类似的问题,现在我知道我们还有更多的选择: varStatus =&#34; loop&#34;,这将是loop将变量,它将保存lop的索引。

它可以用于读取Zeor基本索引或1个基本索引。

${loop.count}` it will give 1 starting base index.

${loop.index} it will give 0 base index as normal Index of array从0开始。

例如:

<c:forEach var="currentImage" items="${cityBannerImages}" varStatus="loop">
<picture>
   <source srcset="${currentImage}" media="(min-width: 1000px)"></source>
   <source srcset="${cityMobileImages[loop.count]}" media="(min-width:600px)"></source>
   <img srcset="${cityMobileImages[loop.count]}" alt=""></img>
</picture>
</c:forEach>

有关详细信息,请参阅此link

答案 2 :(得分:11)

您可以使用varStatus这样的属性: -

<c:forEach var="categoryName" items="${categoriesList}" varStatus="myIndex">

myIndex.index 会为您提供索引。此处myIndexLoopTagStatus对象。

因此,您可以将其发送到您的javascript方法,如下所示: -

<a onclick="getCategoryIndex(${myIndex.index})" href="#">${categoryName}</a>

答案 3 :(得分:0)

$ {类别名称}

以上行给了我错误。所以我用下面的方式写下来,这对我来说很好。 &#39;)&#34; HREF =&#34;#&#34;&GT; $ {类别名称}

可能是别人可能会得到同样的错误。看看这些家伙!!

答案 4 :(得分:0)

这对我有用:

<c:forEach var="i" begin="1970" end="2000">
    <option value="${2000-(i-1970)}">${2000-(i-1970)} 
     </option>
</c:forEach>
相关问题