Bootstrap5环境下如何通过Thymeleaf传id到模态框修改onclick属性
Bootstrap5 传递ID到模态框的实现方案
现有代码问题梳理
- 同时混用Bootstrap4的
data-target和Bootstrap5的data-bs-target属性,逻辑冲突 - 触发按钮的
data-bs-target指向固定的#modal-view,但模态框ID是动态生成的modal-warning+${id},二者不匹配,模态框本身无法正常触发 - 用Thymeleaf为每个用户单独生成模态框的写法冗余,占用不必要的DOM资源
- jQuery拿到ID后没有完成对模态框按钮属性的赋值逻辑,属于逻辑断层
方案1:Bootstrap5 原生模态框事件实现(推荐)
不需要生成多个模态框,共用1个模态框动态修改属性即可,符合Bootstrap5的设计规范:
1. 修改触发按钮代码
把用户ID存在自定义data-bs-*属性中,固定指向同一个模态框:
<tr th:each="user: ${users}"> <a data-bs-toggle="modal" title="active" th:data-bs-user-id="${user.id}" data-bs-target="#modal-view"> inactivate </a> </tr>
2. 调整模态框代码
只保留一个公共模态框,给确认按钮加固定ID方便选择:
<div th:fragment="modal" class="modal fade modal-warning" id="modal-view" tabindex="-1" aria-labelledby="label-modal-1"> <div class="modal-dialog"> <div class="modal-footer"> <input type="button" id="inactivateBtn" value="确认停用" /> </div> </div> </div>
3. 补充JS逻辑
用Bootstrap5原生的show.bs.modal事件获取触发元素的ID,动态修改按钮跳转地址:
$(document).ready(function() { const modal = document.getElementById('modal-view') // 监听模态框显示事件 modal.addEventListener('show.bs.modal', function (event) { // 获取触发当前模态框的按钮元素 const triggerBtn = event.relatedTarget // 读取按钮上存的用户ID const userId = triggerBtn.getAttribute('data-bs-user-id') // 给模态框确认按钮绑定跳转逻辑 const inactivateBtn = document.getElementById('inactivateBtn') inactivateBtn.onclick = () => location.href = `/inactivate/${userId}` }) })
方案2:补全现有jQuery逻辑
如果不想改动原有结构,直接补全你现有代码的断层逻辑即可:
$(document).ready(function() { $('[title="active"]').click(function() { const userId = $(this).attr('id') // 直接修改模态框确认按钮的onclick属性 $('#inactivateBtn').attr('onclick', `location.href='/inactivate/${userId}'`) }) })
可替代轻量实现思路
如果模态框只有二次确认的作用,不需要复杂内容,可以不用写模态框代码,直接用原生confirm实现更简洁:
<tr th:each="user: ${users}"> <a th:onclick="|if(confirm('确认要停用该用户吗?')) location.href='/inactivate/${user.id}'|" > inactivate </a> </tr>
内容的提问来源于stack exchange,提问作者Gustavo
相关产品推荐
相关产品推荐

