关于Thymeleaf中onclick的坑

本文讲述了在使用SpringBoot和Thymeleaf时,遇到在button标签的onclick事件中使用model参数的问题。原始写法因数据类型限制报错,通过将变量用`[[`包裹解决,虽然无误但引发视觉不适。作者分享了解决过程和经验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近学了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>

 结果出现这样的问题:

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

感谢这篇帖子thymeleaf 的 th:onclick,慢慢采坑_thymeleaf th:onclick-CSDN博客

### 在Thymeleaf中动态设置`onclick`属性值 在Thymeleaf模板引擎中,可以通过表达式语法动态设置HTML元素的属性值,包括`onclick`属性。以下是一个详细的示例,展示如何实现这一功能: ```html <!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>动态设置onclick属性</title> </head> <body> <!-- 动态设置按钮的onclick属性 --> <button th:onclick="'javascript:showMessage(\'' + ${message} + '\')'">点击我</button> <script> // 定义一个简单的JavaScript函数,用于接收从Thymeleaf传递的参数 function showMessage(message) { alert(message); } </script> </body> </html> ``` 在这个示例中,`th:onclick`属性被用来动态生成一个带有参数的`onclick`事件处理程序[^1]。通过使用字符串拼接的方式,将后台传入的变量`${message}`嵌入到JavaScript函数调用中。 此外,如果需要传递多个参数,可以扩展此方法。例如: ```html <button th:onclick="'javascript:openBox(\'' + ${curCabNo} + '\',\'' + ${box.no} + '\')'">打开盒子</button> ``` 上述代码片段展示了如何通过Thymeleaf的表达式语法动态构造`onclick`属性值,并确保能够正确调用JavaScript函数[^2]。 需要注意的是,在某些情况下,可能需要使用转义字符(如`\`)来避免语法冲突。例如,当字符串中包含单引号时,必须对其进行转义以保证HTML和JavaScript代码的正确性[^3]。 尽管Thymeleaf提供了强大的模板功能,但在现代前端开发中,推荐使用MVVM框架(如Vue.js)来简化数据绑定和事件处理逻辑[^2]。 --- ###
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值