首先,吐槽一下。这个问题搞得我很无语。最后有种撞了南墙的感觉。
问题描述
众所周知,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。
原因分析
分析代码,感觉没有问题。
可是,经过尝试,发现:如果th:each标签搭配tr和td出现的话,必须作用在tr之前,不可加在div上。
解决方案
将th:each标签加在tr上之后,可以直接取值index,即行状态。然后搭配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>
网友评论