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

Thymeleaf片段传递字符串作为onchange方法出错求助

解决Thymeleaf片段传递onchange字符串参数报错的问题

你的问题出在th:onchange="${__${onchange}__}"的语法上——这种双重表达式解析会让Thymeleaf把你传入的theMethod()当成服务器端方法去查找执行,而非直接输出为客户端JS代码,所以才会报“Method call: theMethod() cannot be found”的错误。

下面是两种可行的修复方案:

方案一:使用th:attr设置属性

直接通过th:attr指定onchange属性,避免Thymeleaf对属性值做额外的表达式解析:

<!-- fragment.html 修改后 -->
<span th:fragment="myInput(id, onchange)">
   <select th:id="${id}" th:attr="onchange=${onchange}">
      <!-- 选项内容 -->
   </select>
</span>

方案二:使用字符串拼接语法|...|

用Thymeleaf的字符串拼接语法包裹参数,让它直接输出为字符串内容:

<!-- fragment.html 修改后 -->
<span th:fragment="myInput(id, onchange)">
   <select th:id="${id}" th:onchange="|${onchange}|">
      <!-- 选项内容 -->
   </select>
</span>

为什么原写法失效?

${__${onchange}__}属于双重表达式计算:Thymeleaf会先解析内层的${onchange}得到字符串theMethod(),接着会把这个字符串当作新的Thymeleaf表达式去执行——也就是尝试调用服务器端的theMethod()方法,但这个方法在后端不存在,因此触发报错。

修改后,传递的'theMethod()'会直接渲染为客户端的onchange="theMethod()",只要你的JS文件正确引入或函数已在页面定义,就能正常触发执行。

内容的提问来源于stack exchange,提问作者CDA the Programmer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 21:35:28