如何为Bootstrap Modal的data-bs-target设置动态ID?
Bootstrap模态框Thymeleaf动态ID绑定失效修复
问题原因
你的写法失效主要有3个核心问题:
- 原生
data-bs-target属性内直接写${}表达式,Thymeleaf引擎不会解析这部分内容,最终输出的target值就是你写的原字符串,不会替换成动态ID值 - 表达式拼接时前后加了多余空格,会导致最终生成的ID、target值带无意义空白字符,两者无法匹配
- 如果
question.question_id是数字类型,直接把数字放在ID开头不符合HTML的ID命名规范,会出现选择器匹配兼容性问题
正确实现代码
首先调整模态框的ID绑定逻辑,把固定前缀放在ID最前面,去掉多余空格:
<div class="modal" th:id="'question_editModal_' + ${question.question_id}"> <!-- 模态框内部原有业务代码保持不变即可 --> </div>
触发按钮的data-bs-target需要用Thymeleaf的属性绑定语法赋值,两种写法都可以正常生效:
写法1:通用th:attr绑定(兼容所有Thymeleaf版本)
<button type="button" class="btn btn-primary" data-bs-toggle="modal" th:attr="data-bs-target='#question_editModal_' + ${question.question_id}"> Edit Question </button>
写法2:th:data-*专属绑定(写法更简洁,推荐使用)
<button type="button" class="btn btn-primary" data-bs-toggle="modal" th:data-bs-target="'#question_editModal_' + ${question.question_id}"> Edit Question </button>
校验提示:渲染后可以打开浏览器开发者工具,查看最终生成的模态框id属性值、按钮的data-bs-target属性值,确认两者除了target前带
#之外其余部分完全一致,即可正常触发模态框。
内容的提问来源于stack exchange,提问作者IU Kottahchchi
相关产品推荐
相关产品推荐

