Thymeleaf 给 onclick 赋值:语法、多参数及字符串处理
Thymeleaf 给 onclick 赋值
基本语法
Thymeleaf 给 onclick 赋值的语法如下:
<button th:onclick="'javascript:myFunction('' + ${variableName} + '');'">Click me</button>
其中,${variableName} 是 Thymeleaf 中的变量名,可以替换为具体的变量值。myFunction 是 JavaScript 函数的名称。在 onclick 中,我们使用单引号将整个 JavaScript 代码包含起来,并使用加号将变量值拼接在一起。
给 onclick 赋值多个参数
如果要给一个 onclick 赋多个参数,可以使用逗号将参数分隔开。例如:
<button th:onclick="'javascript:myFunction('' + ${param1} + '','' + ${param2} + '');'">Click me</button>
其中,${param1} 和 ${param2} 是 Thymeleaf 中的变量名,可以替换为具体的变量值。在 onclick 中,我们使用单引号将整个 JavaScript 代码包含起来,并使用加号将变量值拼接在一起。myFunction 是 JavaScript 函数的名称,其中包含两个参数。点击按钮时,会将 ${param1} 和 ${param2} 作为参数传递给 JavaScript 函数。
字符串处理
如果要在 Thymeleaf 表达式中使用字符串,可以使用单引号将字符串括起来,例如:
<p th:text="'Hello, ' + ${name} + '!'" />
其中,${name} 是 Thymeleaf 中的变量名,可以替换为具体的变量值。在表达式中,使用加号将字符串和变量拼接在一起。这样就可以在 Thymeleaf 中使用字符串了。
常见报错解决
错误信息: 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.
原因: 该报错意味着在 Thymeleaf 表达式中,只有返回数字或布尔值的变量表达式是被信任的,其他类型的数据,如字符串或其他可以被渲染为文本字面值的对象,都不被信任。这通常是因为在表达式中使用了不被信任的数据类型,需要检查表达式中使用的变量类型是否正确。
解决方法: 使用单引号将字符串括起来,并将字符串和变量使用加号拼接在一起。
代码示例
<button id="modal-open-btn-1" data-modal-open="modal-1" th:onclick="'select_city('' + ${addresss.getProvience()} + '','' + ${addresss.getCity()} + '','' + ${addresss.getAddressLine()} + '','' + ${addresss.getPhone()} + '','' + ${addresss.getIsDefault().toString()} + '')'" class="btn btn-primary">修改地址</button>
这段代码中使用 Thymeleaf 给按钮元素绑定了一个 onclick 事件,当按钮被点击时,会执行 JavaScript 函数 select_city,并将 addresss 对象中的省、市、地址、电话和是否默认等参数作为函数的参数传递进去。注意在表达式中使用单引号将参数括起来,并使用加号将参数和字符串拼接在一起。
原文地址: https://www.cveoy.top/t/topic/nzIX 著作权归作者所有。请勿转载和采集!