【问题标题】:JSTL: iterate list but treat first element differentlyJSTL:迭代列表但以不同方式处理第一个元素
【发布时间】:2011-01-02 07:55:48
【问题描述】:

我正在尝试使用 jstl 处理列表。我想以不同于其他元素的方式处理列表的第一个元素。也就是说,我只希望第一个元素将显示设置为阻止,其余的应该隐藏。

我所拥有的似乎臃肿,并且不起作用。

感谢您的帮助。

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

【问题讨论】:

    标签: java jstl jsp-tags


    【解决方案1】:

    是的,在 foreach 元素中声明 varStatus="stat",这样您就可以询问它是第一个还是最后一个。它是 LoopTagStatus 类型的变量。

    这是 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>
    

    已编辑:从 axtavt 复制

    如果没有&lt;c:if&gt;,它可以做得更短:

    <c:forEach items="${learningEntry.samples}" var="sample" varStatus = "status">
        <table class="sampleEntry" ${status.first ? '' : 'style = "display:none"'}> 
    </c:forEach> 
    

    【讨论】:

      【解决方案2】:

      如果没有&lt;c:if&gt;,它可以做得更短:

      <c:forEach items="${learningEntry.samples}" var="sample" varStatus = "status">
          <table class="sampleEntry" ${status.first ? '' : 'style = "display:none"'}> 
      </c:forEach> 
      

      【讨论】:

      • 根据用例,您还可以在 foreach 循环中使用 when 语句 &lt;c:when test="${status.first }"&gt;&lt;/c:when&gt;
      猜你喜欢
      • 2018-06-04
      • 1970-01-01
      • 2011-01-26
      • 2021-02-14
      • 2020-09-06
      • 1970-01-01
      • 2016-09-21
      • 2013-01-19
      • 1970-01-01
      相关资源
      最近更新 更多