首先,吐槽一下。這個問題搞得我很無語。最后有種撞了南墻的感覺。
問題描述
眾所周知,Thymeleaf框架的th:each標簽很好用,相較于freemaker而言,更加簡練。但是如果遇到,表格對應tr隔行變色的問題,就顯得有些力不從心了。
比如:
<div th:if="${typeList!=null && typeList.size()>0}">
<div th:each="type,index:${typeList}" >
<tr th:if="${index.odd}" class="odd">
<td align="center" th:text="${type.typeId}"></td>
<td align="center" th:text="${type.typeName}"></td>
<td align="center">
<button th:onclick="'javascript:window.location.href=\'/admin/website/imagesPage?websiteImages.typeId='+${type.typeId}+'\''" class="ui-state-default ui-corner-all" type="button">查看廣告圖</button>
<button th:onclick="'javascript:updateType('+${type.typeId}+',this)'" class="ui-state-default ui-corner-all" type="button">修改名稱</button>
<button th:onclick="'javascript:deleteType('+${type.typeId}+')'" class="ui-state-default ui-corner-all" type="button">刪除</button>
</td>
</tr>
</div>
<tr th:unless="${index.odd}" class="odd">
<td align="center" th:text="${type.typeId}"></td>
<td align="center" th:text="${type.typeName}"></td>
<td align="center">
<button th:onclick="'javascript:window.location.href=\'/admin/website/imagesPage?websiteImages.typeId='+${type.typeId}+'\''" class="ui-state-default ui-corner-all" type="button">查看廣告圖</button>
<button th:onclick="'javascript:updateType('+${type.typeId}+',this)'" class="ui-state-default ui-corner-all" type="button">修改名稱</button>
<button th:onclick="'javascript:deleteType('+${type.typeId}+')'" class="ui-state-default ui-corner-all" type="button">刪除</button>
</td>
</tr>
</div>
</div>
如上代碼可以實現隔行變色嗎?
答案好像不是很樂觀。報錯了。提示index為null。
原因分析
分析代碼,感覺沒有問題。
可是,經過嘗試,發(fā)現:如果th:each標簽搭配tr和td出現的話,必須作用在tr之前,不可加在div上。
解決方案
將th:each標簽加在tr上之后,可以直接取值index,即行狀態(tài)。然后搭配th:class標簽即可實現上述功能。
該問題折騰了整整一晚上,完全沒想到會有這種操作。
<div th:if="${typeList!=null && typeList.size()>0}">
<tr th:class="${index.odd}?'odd'" th:each="type,index:${typeList}">
<td align="center" th:text="${type.typeId}"></td>
<td align="center" th:text="${type.typeName}"></td>
<td align="center">
<button th:onclick="'javascript:window.location.href=\'/admin/website/imagesPage?websiteImages.typeId='+${type.typeId}+'\''" class="ui-state-default ui-corner-all" type="button">查看廣告圖</button>
<button th:onclick="'javascript:updateType('+${type.typeId}+',this)'" class="ui-state-default ui-corner-all" type="button">修改名稱</button>
<button th:onclick="'javascript:deleteType('+${type.typeId}+')'" class="ui-state-default ui-corner-all" type="button">刪除</button>
</td>
</tr>
</div>