ChatGPT解决这个技术问题 Extra ChatGPT

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

我在 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()"


P
Paul Gray

使用 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>

我知道此Uncaught ReferenceError: 循环未定义 ` 并为您的努力 +1
onClick 显示的元素
因为 varStatus 值包含循环迭代的值。之后,该值无效。所以只有你有例外。您需要索引的目的
我需要知道每个元素的索引 [位置] 都在字符串数组中。
它有效:) 如果我这样做 onclick="getCategoryIndex(${loop.index})" ...感谢您的帮助
J
Jacob van Lingen

我遇到了类似的问题。经过研究,我了解到我们对 varStatus="loop" 有更多选择。它可以使用基于零的索引或基于一的索引:

${loop.index} 使用 0 基础索引

${loop.count} 使用 1 个基本索引

例如 :

<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


R
Rahul

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

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

myIndex.index 将为您提供索引。这里 myIndex 是一个 LoopTagStatus 对象。

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

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

我收到此 Uncaught ReferenceError: myIndex is not defined 和 +1 以感谢您的努力
I
Igor

这对我有用:

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

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

上面的行给了我一个错误。所以我用下面的方式写下来,这对我来说很好。

<a onclick="getCategoryIndex('<c:out value="${myIndex.index}"/>')" href="#">${categoryName}</a>

也许其他人可能会遇到同样的错误。看看这些家伙!