SpringBoot & Thymeleaf循环问题:重复生成删除按钮求助
解决Thymeleaf遍历数组时删除按钮重复生成的问题
你的问题根源在于在每一行<tr>内部又嵌套遍历了idList,导致每一行都会生成和idList长度相同的ID列与删除按钮,而非每行对应一组描述、ID和按钮。下面提供两种可行的解决方法:
方法一:后端封装统一对象(推荐)
最规范的方式是把描述和ID封装成一个实体对象,后端传递包含该对象的列表到前端,这样遍历的时候可以直接获取每行对应的所有属性,避免列表对应错误。
假设后端用Java,先定义一个Wish类:
public class Wish { private String description; private Long id; // 生成getter、setter方法 }
在控制器中把数据封装为List<Wish>并传入模型:
List<Wish> wishList = new ArrayList<>(); // 向列表中填充包含description和id的Wish对象 model.addAttribute("wishList", wishList); model.addAttribute("email", email);
前端Thymeleaf代码修改为:
<table> <tr th:each="wish : ${wishList}"> <!-- 描述列 --> <td th:text="${wish.description}"></td> <!-- ID列 --> <td th:text="${wish.id}"></td> <!-- 删除按钮列 --> <td> <form action="/deletewish" method="post"> <input type="hidden" name="email" th:value="${email}"> <input type="hidden" name="wish_id" th:value="${wish.id}"> <button type="submit">Delete</button> </form> </td> </tr> </table>
方法二:前端通过索引对应两个列表(临时方案)
如果暂时无法修改后端代码,可以利用Thymeleaf迭代时的状态对象获取索引,用索引匹配descriptionList和idList中对应的元素。注意这种方法要求两个列表的长度必须完全一致,否则会出现数据不匹配或越界问题。
<table> <tr th:each="description, stat : ${descriptionList}" th:if="${stat.index < #lists.size(idList)}"> <!-- 描述列 --> <td th:text="${description}"></td> <!-- 通过索引获取对应ID --> <td th:text="${idList[stat.index]}"></td> <!-- 删除按钮,同样用索引获取对应ID --> <td> <form action="/deletewish" method="post"> <input type="hidden" name="email" th:value="${email}"> <input type="hidden" name="wish_id" th:value="${idList[stat.index]}"> <button type="submit">Delete</button> </form> </td> </tr> </table>
th:if="${stat.index < #lists.size(idList)}"用于防止当descriptionList长度大于idList时出现索引越界的情况。
内容的提问来源于stack exchange,提问作者Ian Justino
相关产品推荐
相关产品推荐

