Java JSTL:迭代列表但区别对待第一个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2017753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSTL: iterate list but treat first element differently
提问by D.C.
I'm trying to process a list using jstl. I want to treat the first element of the list differently than the rest. Namely, I want only the first element to have display set to block, the rest should be hidden.
我正在尝试使用 jstl 处理列表。我想以不同于其他元素的方式对待列表的第一个元素。也就是说,我只希望第一个元素的显示设置为阻止,其余的应该隐藏。
What I have seems bloated, and does not work.
我所拥有的似乎臃肿,并且不起作用。
Thanks for any help.
谢谢你的帮助。
<c:forEach items="${learningEntry.samples}" var="sample">
<!-- only the first element in the set is visible: -->
<c:if test="${learningEntry.samples[0] == sample}">
<table class="sampleEntry">
</c:if>
<c:if test="${learningEntry.samples[0] != sample}">
<table class="sampleEntry" style="display:hidden">
</c:if>
采纳答案by axtavt
It can be done even shorter, without <c:if>
:
它可以做得更短,没有<c:if>
:
<c:forEach items="${learningEntry.samples}" var="sample" varStatus = "status">
<table class="sampleEntry" ${status.first ? '' : 'style = "display:none"'}>
</c:forEach>
回答by helios
Yes, declare varStatus="stat" in the foreach element, so you can ask it if it's the first or the last. Its a variable of type LoopTagStatus.
是的,在 foreach 元素中声明 varStatus="stat",这样你就可以问它是第一个还是最后一个。它是一个 LoopTagStatus 类型的变量。
This is the doc for LoopTagStatus: http://java.sun.com/products/jsp/jstl/1.1/docs/api/javax/servlet/jsp/jstl/core/LoopTagStatus.htmlIt has more interesting properties...
这是 LoopTagStatus 的文档:http: //java.sun.com/products/jsp/jstl/1.1/docs/api/javax/servlet/jsp/jstl/core/LoopTagStatus.html它有更多有趣的属性......
<c:forEach items="${learningEntry.samples}" var="sample" varStatus="stat">
<!-- only the first element in the set is visible: -->
<c:if test="${stat.first}">
<table class="sampleEntry">
</c:if>
<c:if test="${!stat.first}">
<table class="sampleEntry" style="display:none">
</c:if>
Edited: copied from axtavt
编辑:从 axtavt 复制
It can be done even shorter, without <c:if>
:
它可以做得更短,没有<c:if>
:
<c:forEach items="${learningEntry.samples}" var="sample" varStatus = "status">
<table class="sampleEntry" ${status.first ? '' : 'style = "display:none"'}>
</c:forEach>