欢迎来到徐庆高(Tea)的个人博客网站
磨难很爱我,一度将我连根拔起。从惊慌失措到心力交瘁,我孤身一人,但并不孤独无依。依赖那些依赖我的人,信任那些信任我的人,帮助那些给予我帮助的人。如果我愿意,可以分裂成无数面镜子,让他们看见我,就像看见自己。察言观色和模仿学习是我的领域。像每个深受创伤的人那样,最终,我学会了随遇而安。
当前位置: 日志文章 > 详细内容

解决Thymeleaf中onclick的坑

2025年08月06日 Java
thymeleaf中onclick的坑最近学了springboot,springboot推荐使用thymeleaf模板,所以一直在用,然后发现许许多多的坑,这次就说说其中关于onclick的坑。在一个

thymeleaf中onclick的坑

最近学了springboot,springboot推荐使用thymeleaf模板,所以一直在用,然后发现许许多多的坑,这次就说说其中关于onclick的坑。

在一个button元素中,需要调用js的方法,并且传递两个来自model的参数,一开始我是这么写的

<button 
    th:onclick=" 'cookover(' + ${item.getoid()} + ',' + ${item.getfid()} + ')' " >出餐
</button>

接下来加载html就报错了

报错信息如下:

org.thymeleaf.exceptions.templateprocessingexception: only variable expressions returning numbers or booleans are allowed in this context, any other datatypes are not trusted in the context of this expression, including strings or any other object that could be rendered as a text literal. a typical case is html attributes for event handlers (e.g. "onload"), in which textual data from variables should better be output to "data-*" attributes and then read from the event handler. (template: "/manage/cookwindow" - line 32, col 13)

神奇的是:同一个项目中的另一个html中,也是这样的写法,没有报错,成功运行,参数传递也都没有问题。

百思不得其解

于是到网上查了下,发现还有一种另写法,我就试了试

<button 
    th:onclick="cookover([[${item.getoid()}]],[[${item.getfid()}]])">出餐
</button>

结果出现这样的问题:

这个问题很神奇,不影响正常运行,但这个红色波浪线让我非常难受

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。