我有一个JSP,在这里我通过JSTL c:forEach循环显示元素。这是一个嵌套循环,如下所示:
<c:forEach items="${auditBudgetData.auditBudgetTierOneList}" var="auditBudgetTierOne" varStatus="tierOneCount">
** Some Code **
<c:forEach items="${auditBudgetTierOne.auditBudgetTierTwoList}" var="auditBudgetTierTwo" varStatus="tierTwoCount">
** Some Code **
<c:forEach items="${auditBudgetTierTwo.auditBudgetItemList}" var="auditBudgetItem" varStatus="budgetItemCount">
<input type="hidden" name="tierOneIndex" value="${tierOneCount.count}">
<input type="hidden" name="tierTwoIndex" value="${tierTwoCount.count}">
<input type="hidden" name="budgetItemIndex" value="${budgetItemCount.count}">
**Element rows displayed here**
现在,当用户在最内层循环中选择任何元素行时,我必须在JS中获取值。如您所见,我正在尝试获取每个嵌套循环的计数,如下所示:
<input type="hidden" name="tierOneIndex" value="${tierOneCount.count}">
<input type="hidden" name="tierTwoIndex" value="${tierTwoCount.count}">
<input type="hidden" name="budgetItemIndex" value="${budgetItemCount.count}">
并尝试如下获取JS中输入字段的值:
var tierOneIndex = $('input[name="tierOneIndex"]').val();
var tierTwoIndex = $('input[name="tierTwoIndex"]').val();
var budgetItemIndex = $('input[name="budgetItemIndex"]').val();
但是无论我选择什么元素,我总会得到:
tierOneIndex = 0
tierTwoIndex = 0
budgetItemIndex = 0
关于如何获取计数值的任何想法。
在您的html中,您可以这样做[>]
<table> <c:forEach items="${auditBudgetData.auditBudgetTierOneList}" var="auditBudgetTierOne" varStatus="tierOneCount"> ** Some Code ** <c:forEach items="${auditBudgetTierOne.auditBudgetTierTwoList}" var="auditBudgetTierTwo" varStatus="tierTwoCount"> ** Some Code ** <c:forEach items="${auditBudgetTierTwo.auditBudgetItemList}" var="auditBudgetItem" varStatus="budgetItemCount"> <input type="hidden" name="tierOneIndex" id="tierOneIndex_${budgetItemCount.index}" value="${tierOneCount.count}"> <input type="hidden" name="tierTwoIndex" id="tierTwoIndex_${budgetItemCount.index}" value="${tierTwoCount.count}"> <input type="hidden" name="budgetItemIndex" id ="budgetItemIndex_${budgetItemCount.index}" value="${budgetItemCount.count}"> <tr class="rows" id="${budgetItemCount.index}"><td>click Here</td></tr> </table>
并且在javascript中,您可以这样做
$(document).ready(function(){ $("tr.rows").click(function() { var rowid=this.id; var tierOneIndex = $('#tierOneIndex_'+rowid).val(); var tierTwoIndex = $('#tierTwoIndex_'+rowid).val(); var budgetItemIndex = $('#budgetItemIndex_'+rowid).val(); console.log("tierOneIndex:"+tierOneIndex); console.log("tierTwoIndex:"+tierTwoIndex); console.log("budgetItemIndex:"+budgetItemIndex); }); });
注意:
[${tierOneCount.index}
从0开始计数
[${tierOneCount.count}
从1开始计数
我也为您创建了一个样本小提琴http://jsfiddle.net/9CHEb/33/
如果提交了此页面,如何在提交的页面中访问这些隐藏变量?(请参阅一周前询问的问题“在forEach循环中访问JSTL变量,并将varStatus计数作为JSP中变量的一部分”)