thymeleaf中onclick事件动态传递参数问题


1. 动态传递Number类型或Boolean类型

1.1 动态传递一个Number 类型

<button th:onclick="|test(${session.friend.id})|">测试</button>

1.2 动态传递一个Boolean类型

  • 示例一:
 <button th:onclick="|test(${session.userBasic.id == session.friend.id})|">测试一下</button>
  • 示例二:
<button th:onclick="|test(${true})|">测试一下</button>

2. 动态传递字符串类型

如果传递的类型是一个字符串或者对象类型的数据则会报以下错误:

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: "index" - line 26, col 82)

原因是,我们在动态传递参数时用到了 ${} 语法,而这个语法不支持传递字符串或对象类型的数据,此时我们可以通过以下方式动态传递一个字符串:

备注:th:data中的data只是一个变量名,可以修改为其他的具有语义化的名称

<button th:data="${session.userBasic.nickName}" th:onclick="|out(this.getAttribute('data'))|">测试</button>

3. 动态传递多个参数

  • 参数中不包含字符串(多个参数之间使用,隔开)
<button th:onclick="|test(${session.user.id},${session.user.age})|">
  • 参数中包含字符串(多个参数之间使用,隔开)
<button th:data="${session.user.nickName}" th:onclick="|test(${session.user.id},${session.user.age},this.getAttribute('data'))|">

4. 说明

  • 如果只是传递一个固定的参数,并且没有用到 ${} 语法的话,则不需要使用拼接字符 || ,如下所示的格式
<button th:onclick="test(123456)">
<button th:onclick="test('字符串')">
  • 如果需要动态传递参数的话,则必须使用 ${} 语法,那么我们的方法就必须要使用拼接字符 ||进行包裹,如下所示的格式
<button th:onclick="|test(${session.user.id})|">

只要方法的参数中用到了 ${} 语法,那么我们就必须要使用拼接字符 || 将我们的方法进行包裹。

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

☆*往事随風*☆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值