首页 > 解决方案 > Thymeleaf-如何在 th:each 循环内绑定 div 上的点击事件

问题描述

我正在使用 thymeleaf foreach 循环来遍历我的数据。问题是由于它在 foreach 循环中,所有 div 都具有相同的 id,即“delDiv”。当我点击它时,它总是会显示第一个 div。

  <div id="delDiv" sec:authorize="hasAuthority('ROLE_ADMIN')">
                                    <input type="hidden" id="resultId" th:value="${result.getId()}">
                                    <i class="fa fa-trash deleteBadge"></i>
                                </div>
                                <div class="timeDiv" style="" th:text="${result.getUpdatedAt()}"></div>

我希望为 foreach 循环创建的每个新 div 有不同的点击次数。这就是我使用 foreach thymeleaf 生成新行的方式

   <div class="row" th:each="result:${recog}"> My above code is inside this
</div

请帮忙

标签: htmlthymeleaf

解决方案


您应该通过向 div id 添加索引来唯一区分您的 div,如下所示(只需为此使用 Thymeleaf 循环助手):

<div class="row" th:each="result, iterHelper :${recog}">
 <div id="'delDiv__${iterHelper.index}__'" sec:authorize="hasAuthority('ROLE_ADMIN')">
  <input type="hidden" id="resultId" th:value="${result.getId()}"><i class="fa fa-trash deleteBadge"></i></div><div class="timeDiv" style="" th:text="${result.getUpdatedAt()}"></div>
</div

请遵循以获取更多详细信息。特别是第 6.2 节


推荐阅读