You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Thymeleaf中如何通过JS函数传递Spring模型属性参数?

解决Thymeleaf中向JS函数传递模型ID的语法错误问题

你的核心问题是Thymeleaf渲染后JS参数的引号处理不当:如果user.uid是字符串类型,直接写onclick="deleteUser(${user.uid})"会导致渲染后的HTML缺少字符串引号,触发JS语法错误;即使是数字类型,这种写法也不够严谨。以下是两种可靠的解决方式:

方法1:使用Thymeleaf内联表达式(快速修正)

利用Thymeleaf的[[${}]]内联语法,它会自动根据变量类型添加引号(字符串加单引号,数字则不加),避免手动拼接引号的麻烦:

<div th:each="user:${us}" class="student-bubble" draggable="true" >
    <div th:text="${user.name}" class="student-name"></div>
    <div th:text="${user.email}" class="student-info"></div>
    <div th:text="${user.gpa}" class="student-info"></div>
    <div th:text="${user.height}" class="student-info"></div>

    <div class="buttons">
        <button class="edit-button" th:onclick="editUser(event, [[${user.uid}]])">Edit</button>
        <button class="delete-button" th:onclick="deleteUser([[${user.uid}]])">Delete</button>
    </div>
</div>

渲染后如果uid是字符串"user_001",会生成符合JS语法的代码:

<button class="edit-button" onclick="editUser(event, 'user_001')">Edit</button>

方法2:使用data属性+事件委托(推荐,分离结构与行为)

这种方式将ID存储在HTML的data-*属性中,通过JS事件委托绑定逻辑,更符合现代前端开发规范,也彻底避免引号问题:

HTML 部分

<div th:each="user:${us}" class="student-bubble" draggable="true" >
    <div th:text="${user.name}" class="student-name"></div>
    <div th:text="${user.email}" class="student-info"></div>
    <div th:text="${user.gpa}" class="student-info"></div>
    <div th:text="${user.height}" class="student-info"></div>

    <div class="buttons">
        <button class="edit-button" data-uid="${user.uid}">Edit</button>
        <button class="delete-button" data-uid="${user.uid}">Delete</button>
    </div>
</div>

JavaScript 部分

// 监听全局点击事件,通过事件委托处理按钮点击
document.addEventListener('click', function(e) {
    const targetBtn = e.target;
    // 获取按钮上的uid数据
    const uid = targetBtn.dataset.uid;
    if (!uid) return;

    // 判断按钮类型并调用对应函数
    if (targetBtn.classList.contains('edit-button')) {
        editUser(e, uid);
    } else if (targetBtn.classList.contains('delete-button')) {
        deleteUser(uid);
    }
});

这种写法的优势:

  • 彻底分离HTML结构和JS逻辑,代码更易维护
  • 避免了Thymeleaf与JS引号冲突的问题
  • 即使后续新增按钮,也无需修改HTML绑定逻辑

内容的提问来源于stack exchange,提问作者brian lee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 09:09:57