Variable expression into javascript without using th:inline

泪湿孤枕 提交于 2019-11-27 03:21:00

问题


I searched first but I found confusing answers since I'm new to Thymeleaf and amateurish at best at javascript.

I just want to know how to pass variable expressions into javascript functions, sort of like in JSP:

<a href="#" onclick="javascript:getContactId('${contact.id}');">Button</a>

Of course, this fails with Thymeleaf and passes the string ${contact.id} instead of its value, so how could I get the value of the variable expression instead?

The reason I want it this way is because it depends on the row which is being iterated by th:each.

If there's no other way except to use th:inline, then what's the best approach considering the above statement?


回答1:


This one worked:

th:onclick="'javascript:getContactId(\'' + ${contact.id} + '\');'"

Thanks goes out to the thymeleaf forum: http://forum.thymeleaf.org/variable-expression-into-javascript-without-using-th-inline-td4025534.html




回答2:


In Thymeleaf version 2.1, I have not been able to get the accepted answer to work. I did find some guidance from a Twitter post from Thymeleaf. Rather than using th:onclick, you use th:attr and specify the onclick attribute therein.

th:attr="onclick='javascript:getContactId(\'' + ${contact.id} + '\');'"



回答3:


You can not put javascript variables into onclick or other DOM attributes. The value of onclick or any other DOM attribute should be a constant string.

However, you can dynamically modify value of onclick attribute from javascript, like this:

yourDomElement.onclick = anyVariable;



回答4:


You can do this like:

th:onclick="'javascript:getContactId(\'' + ${contact.id} + '\');'"




回答5:


A more generic approach, if you need in JS something that isn't passed as a event handler parameter:

th:attr="data-myValueFromThymeleaf=${contact.id}"

Any attribute whose name is starting with data- is ignored by all browsers. So it won't affect the UI and you can easily read the value in javascript.

I prefer this because it's not ideal to put javascript code in html (see unobtrusive javascript)




回答6:


I have asked the Thymeleaf project on twitter, and their answer is:

You can use both the "+" operator or literal substitutions. For example: <a th:href="|javascript:change('start','${taskId}')|">

For more info: https://www.thymeleaf.org/doc/articles/standarddialect5minutes.html

I have tried, and it works~



来源:https://stackoverflow.com/questions/14365746/variable-expression-into-javascript-without-using-thinline

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