How to pass arguments to javascript function call when using onClick in Thymeleaf

让人想犯罪 __ 提交于 2020-05-29 07:40:48

问题


I have been calling my javascript function from Thymeleaf as below:

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

But I just updated my spring boot version to 2.1.4 RELEASE with which Thymeleaf also got updated. And the previous version in no longer supported.

On further research I found out that I should be able to use

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

However, it doesn't give any error but neither does it work. I have removed the argument and was able to call the function just fine. So I am guessing I am not passing the argument right way. Any guidance will be helpful. TIA.


回答1:


See this: Restricted mode: Avoid variable expressions returning strings in processors for event handlers (th:on*).

In order to correctly pass Thymeleaf variables to the onclick event, put the variable in a data attribute, and read it using getAttribute().

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



回答2:


You should use it as follows:

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


来源:https://stackoverflow.com/questions/55726362/how-to-pass-arguments-to-javascript-function-call-when-using-onclick-in-thymelea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!