【问题标题】:alternating applying class to tr交替应用类到 tr
【发布时间】:2012-09-04 10:38:01
【问题描述】:

我想在 jsp 页面中交替应用 css 到 thr。下面是我的代码。

<c:forEach var="aff" items="${report}">
        <tr class="**tital_black_second**">
    <input type="hidden" id="org_id" value="${aff.org_id}">
      <td width="74" class="td_text">&nbsp;</td>
      <td width="173" class="heading3 td_text">${aff.string}</td>
      <td width="168" class="td_text text3">${aff.posted}</td>
      <td width="134" class="td_text text3">${aff._sold}</td>
      <td width="118" class="td_text text3">${aff.of_commision}</td>
      <td width="126" class="td_text text3">${affl}</td>
      <td width="115" class="td_text text3"></td>
      <td width="129" class="td_text text3">&nbsp;</td>
</tr>
</c:forEach>

对于每个 tr 交替我想应用类,即当一个 tr 被绘制时,我想要 class="tital_black_second" 并且当第二个被绘制时 class="tital_black_first"。

我怎样才能做到这一点。

提前致谢。

【问题讨论】:

  • 取一个计数器,继续加,检查数值,奇数应用X类,偶数应用Y
  • 谢谢,但任何示例代码都会对我有所帮助。

标签: jsp spring-mvc jstl


【解决方案1】:

您可以在 CSS 或 jQuery 中执行此操作,而不是在 jstl 中执行此操作。

CSS3 有一个:nth-child(arg) 伪类,它允许我们控制交替行的显示。但这仅在现代浏览器中受支持,因此跨浏览器兼容性可能会成为问题。

tr:nth-child(odd)    { background-color:#ffffff; }
tr:nth-child(even)    { background-color:#000000; }

或者在 jQuery 中:

$("tr:odd").css("background-color", "#ffffff");
$("tr:even").addClass("evenRowClass");

【讨论】:

    【解决方案2】:

    您可以使用此处发布的解决方案:How to alternate HTML table row colors using JSP?

    对于您的代码,它将是:

    <c:forEach items="${report}" var="aff" varStatus="loopStatus">
      <tr class="${loopStatus.index % 2 == 0 ? 'tital_black_second' : 'tital_black_first'}">
        <input type="hidden" id="org_id" value="${aff.org_id}">
          <td width="74" class="td_text">&nbsp;</td>
          <td width="173" class="heading3 td_text">${aff.string}</td>
          <td width="168" class="td_text text3">${aff.posted}</td>
          <td width="134" class="td_text text3">${aff._sold}</td>
          <td width="118" class="td_text text3">${aff.of_commision}</td>
          <td width="126" class="td_text text3">${affl}</td>
          <td width="115" class="td_text text3"></td>
          <td width="129" class="td_text text3">&nbsp;</td>
    </tr>
    </c:forEach>
    

    【讨论】:

      【解决方案3】:

      看看even and odd CSS rules。为每一行手动添加类是不必要的开销。

      .yourtable-class tr:nth-child(even) { 
         // styles for your even rows
      }
      
      .yourtable-class tr:nth-child(odd) { 
         // styles for your odd rows
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多