在onclick属性中使用thymeleaf变量

Kle*_*ota 19 javascript spring onclick thymeleaf spring-boot

在我目前的spring-boot项目中,我有一个带有这个html代码的视图:

<button type="button" class="btn btn-primary" onclick="upload()" th:utext="#{modal.save}"></button>
Run Code Online (Sandbox Code Playgroud)

onclick属性中,对函数的调用upload()应该有一个参数,该值存储在thymeleaf变量中${gallery}.

任何人都可以告诉我如何在上面的命令中使用表达式?

我已经尝试过了:

  • th:onclick="upload(${gallery)"

  • th:attr="onclick=upload(${gallery)"

这些都没有奏效.

Kle*_*ota 27

我用这种方法解决了这个问题:

th:onclick="|upload('${command['class'].simpleName}', '${gallery}')|"
Run Code Online (Sandbox Code Playgroud)

  • 现在(2020)它似乎不再起作用:错误:在此上下文中仅允许返回数字或布尔值的变量表达式,任何其他数据类型均不受信任 (2认同)

小智 11

thymeleaf 3.0.10 th:onclick thymeleaf变量不起作用

这应该工作:

th:attr="onclick=|upload('${gallery}')|" 
Run Code Online (Sandbox Code Playgroud)

  • 这是正确的答案,因为从版本 3.0.10 开始,thymeleaf 不支持 `th:onclick="..."` 中除 Boolean 和 Integer 类型的变量。因此,如果您想将非布尔值和非整数参数传递给 `onclick()` 方法,`th:onclick="..."` 将不起作用。您必须使用 `th:attr="onclick=..."` 如本答案所示。 (2认同)

snw*_*snw 10

这应该工作:

<button th:onclick="'javascript:upload(' + ${gallery} + ')'"></button>
Run Code Online (Sandbox Code Playgroud)

  • 这很完美,但你已经省略了右括号'}'.应该是`<button th:onclick ="'javascript:upload('+ $ {gallery} +')'"> </ button>`.如果它是一个String参数,你可能需要将_gallery_括在引号中,所以`<button th:onclick ="'javascript:upload('\'+ $ {gallery} +'\')'"> </ button> `. (2认同)

Eri*_*RAM 7

在 Thymeleaf 3.0.10 版本中

使用 [[]] 更容易,thymeleaf 去注入模板中的值

如果值是字符串,则不需要引号

<button th:data-id="${quartzInfo.id}" 
    th:onclick="del(this,[[${quartzInfo.id}]]" type="button">
</button>
Run Code Online (Sandbox Code Playgroud)


Leo*_*eon 6

旧的回复在新版本3.0.10中不起作用。现在你需要:

<button th:data-id="${quartzInfo.id}" 
    onclick="del(this,this.getAttribute('data-id'))" type="button">
</button>
Run Code Online (Sandbox Code Playgroud)