当前位置:网站首页>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})|">
只要方法的参数中用到了 ${} 语法,那么我们就必须要使用拼接字符 || 将我们的方法进行包裹。
边栏推荐
猜你喜欢

canal实现mysql数据同步

【论文阅读笔记】无监督行人重识别中的采样策略

Can‘t connect to MySQL server on ‘localhost3306‘ (10061) 简洁明了的解决方法

Swoole学习(一)

MySQL日志篇,MySQL日志之binlog日志,binlog日志详解

C1认证之web基础知识及习题——我的学习笔记

企业需要知道的5个 IAM 最佳实践

7.15 Day21---MySQL----Index

Cannot read properties of null (reading 'insertBefore')

word 公式编辑器 键入技巧 | 写数学作业必备速查表
随机推荐
力扣:70. 爬楼梯
Can 't connect to MySQL server on' localhost3306 '(10061) simple solutions
乱码解决方案
力扣:509. 斐波那契数
string类简介
Redis common interview questions
7.15 Day21---MySQL----索引
动态规划总括
TensorRTx-YOLOv5工程解读(二)
梳理CamStyle、PTGAN、SPGAN、StarGAN
8、自定义映射resultMap
FFmpeg源码分析:avformat_open_input
Unity自动生成阻挡Collider的GameObject工具
Camera2 闪光灯梳理
How to view sql execution plan offline collection
腾讯136道高级岗面试题:多线程+算法+Redis+JVM
Handling List
Cannot read properties of null (reading ‘insertBefore‘)
Plus版SBOM:流水线物料清单PBOM
webrtc中视频采集实现分析(一) 采集及图像处理接口封装