当前位置:网站首页>thymeleaf中onclick事件动态传递参数问题
thymeleaf中onclick事件动态传递参数问题
2022-08-04 05:25:00 【**往事随風**】
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})|">
只要方法的参数中用到了 ${}
语法,那么我们就必须要使用拼接字符 ||
将我们的方法进行包裹。
边栏推荐
猜你喜欢
The difference between px, em, and rem
腾讯136道高级岗面试题:多线程+算法+Redis+JVM
Performance testing with Loadrunner
7.15 Day21---MySQL----索引
【论文阅读笔记】无监督行人重识别中的采样策略
8. Custom mapping resultMap
8、自定义映射resultMap
npm报错Beginning October 4, 2021, all connections to the npm registry - including for package installa
心余力绌:企业面临的软件供应链安全困境
What is the salary of a software testing student?
随机推荐
SLSA 框架与软件供应链安全防护
4.1 声明式事务之JdbcTemplate
Typora 使用保姆级教程 | 看这一篇就够了 | 历史版本已被禁用
C language -- operator details
TensorRTx-YOLOv5工程解读(二)
9、动态SQL
LCP 17. 速算机器人
What is the salary of a software testing student?
npm安装依赖报错npm ERR! code ENOTFOUNDnpm ERR! syscall getaddrinfonpm ERR! errno ENOTFOUND
程序员的财富观
梳理CamStyle、PTGAN、SPGAN、StarGAN
Tactile intelligent sharing - SSD20X realizes upgrade display progress bar
7.16 Day22---MYSQL (Dao mode encapsulates JDBC)
Sublime Text 3 2021.8.3 个人配置
LCP 17. Quick Calculation Robot
力扣:746. 使用最小花费爬楼梯
3面头条,花7天整理了面试题和学习笔记,已正式入职半个月
FFmpeg源码分析:avformat_open_input
力扣:63. 不同路径 II
static在不同位置定义变量居然还有不同的含义?