【问题标题】:How to pass arguments to javascript function call when using onClick in Thymeleaf在 Thymeleaf 中使用 onClick 时如何将参数传递给 javascript 函数调用
【发布时间】:2019-09-07 15:07:34
【问题描述】:

我一直在从 Thymeleaf 调用我的 javascript 函数,如下所示:

th:onclick="'viewDocument(\'' + ${document.docTypeLongDesc} +'\');'"

但我刚刚将我的 Spring Boot 版本更新为 2.1.4 RELEASE,Thymeleaf 也随之更新。并且不再支持以前的版本。

经过进一步研究,我发现我应该能够使用

th:onclick="' viewDocument (this.getAttribute ('document.docTypeLongDesc'));'"

但是,它没有给出任何错误,但也不起作用。我已经删除了参数并且能够很好地调用该函数。所以我猜我没有以正确的方式传递论点。任何指导都会有所帮助。 TIA。

【问题讨论】:

    标签: java spring-boot thymeleaf


    【解决方案1】:

    你应该按如下方式使用它:

    th:onclick="${'viewDocument(' + document.docTypeLongDesc + ');'}"
    

    【讨论】:

      【解决方案2】:

      看到这个:Restricted mode: Avoid variable expressions returning strings in processors for event handlers (th:on*)

      为了正确地将 Thymeleaf 变量传递给 onclick 事件,请将变量放在 data 属性中,并使用 getAttribute() 读取它。

      th:data-longDescription="${document.docTypeLongDesc}" onclick="viewDocument(this.getAttribute('data-longDescription'));"
      

      【讨论】:

      • 我引用了相同的链接并以相同的方式使用它,但仍然出现运行时错误:org.thymeleaf.exceptions.TemplateInputException:模板解析期间发生错误(模板:“templates/th_documentsDetails.html” ) . Intellij 也将 this.getAttribute 突出显示为红色,突出显示时表示无法识别。我认为这很可能是某个地方的语法错误。
      • @ILRNew 你有没有注意到我不再使用th:onclick,现在它只是一个普通的onclick,因为它不再需要是一个百里香表达式。
      • 你说得对。我没有注意到这一点。一旦我这样做了,它就像一个魅力。非常感谢您。我能问你如何了解更多关于新 Thymeleaf 的信息吗?
      猜你喜欢
      • 2023-03-19
      • 1970-01-01
      • 2013-12-16
      • 2012-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多