因此,我有一个 JSP 页面,该页面附加到我需要使用 JSTL 循环进行循环的对象列表。 (这是一个 Tiles 项目, Controller 正在设置一些模拟对象,这些对象将被添加到列表中并作为列表返回。这一点工作得很好。) 基本上,我希望它连续显示名称、值和按钮,当单击按钮时,我希望弹出其余信息。
<c:forEach var="i" varStatus="curr" items="${items}">
<tr>
<td>
${i.itemName}
</td>
<td>
${i.itemValue}
</td>
<td style="float:right;">
<input type="button" id="showhide">
</td>
</tr>
<tr>
<td class="toggle">
${i.itemAltName}
${i.itemAdditions}
${i.itemValueAfterAdditions}
</td>
</tr>
</c:forEach>
我正在使用以下 JS。
<script type="text/javascript">
var buttons = document.getElementById('showhide');
buttons.onclick = function() {
var div = document.getElementsByClassName('toggle');
var x = div.length;
for(var i = 0; i < x; ++i){
if (div[i].style.display !== 'none') {
div[i].style.display = 'none';
}
else {
div[i].style.display = 'block';
}
}
};
</script>
另外,在这里说明显而易见的事情,但我的风格区域有:
.toggle{
display:none;
}
目前,只有第一个按钮可以正确打开相应的文本。从我看到的其他答案中,我知道我需要使 ID 唯一,但我不确定如何使用 JSP 循环来做到这一点。帮忙?
最佳答案
与其他答案相比,这是一种不同的方法,使用 varStatus(由 Jozef Chocholacek 建议)来获取唯一 ID。
这将允许您有一个解决方案,无论按钮和链接的 td 在哪里(它们不必是同级)。
您的 JSP:
<c:forEach var="i" varStatus="curr" items="${items}" varStatus="loop">
<tr>
<td>
${i.itemName}
</td>
<td>
${i.itemValue}
</td>
<td style="float:right;">
<input type="button" class="showhide" id="showHideButton_${loop.index}">
</td>
</tr>
<tr>
<td class="toggle" id="data_${loop.index}">
${i.itemAltName}
${i.itemAdditions}
${i.itemValueAfterAdditions}
</td>
</tr>
</c:forEach>
使用下面代码片段中的 JS:
var buttons = document.getElementsByClassName('showhide');
for (var i=0;i<buttons.length;i++) {
buttons[i].addEventListener("click", clickHandler);
}
function clickHandler(event) {
var buttonId = event.target.id;
var rowId = buttonId.split("_")[1];
var rowData = document.getElementById('data_' + rowId);
// do whatever you want with your row
if (rowData.style.display !== 'none') {
rowData.style.display = 'none';
} else {
rowData.style.display = 'block';
}
}
<table>
<tr>
<td>Name</td>
<td>Value</td>
<td>Action</td>
</tr>
<tr>
<td>
Item Name 1
</td>
<td>
Item Value 1
</td>
<td style="float:right;">
<input type="button" class="showhide" id="showHideButton_98" value="Toggle">
</td>
</tr>
<tr>
<td class="toggle" id="data_98">
itemAltName1
itemAdditions1
itemValueAfterAdditions1
</td>
</tr>
<tr>
<td>
Item Name 2
</td>
<td>
Item Value 2
</td>
<td style="float:right;">
<input type="button" class="showhide" id="showHideButton_55" value="Toggle">
</td>
</tr>
<tr>
<td class="toggle" id="data_55">
itemAltName2
itemAdditions2
itemValueAfterAdditions2
</td>
</tr>
关于javascript - JSP/JS forEach 循环中仅打开第一个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46956587/