如何使用 Thymeleaf 动态设置 HTML 元素的 id 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35722528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set the id attribute of HTML element dynamically with Thymeleaf
提问by Lazar Lazarov
Lets say I have an object : ${object}
假设我有一个对象:${object}
and I have the following form:
我有以下表格:
<form id="{{'myForm' + object.id}" class="some class"
th:action="@{/doSomething}" method="post">
....
</form>
My goal is to set the id = "myForm1" if we assume that the object.id is '1'.
如果我们假设 object.id 是“1”,我的目标是设置 id = "myForm1"。
PS: The way I wrote it's working on Angular JS.
PS:我编写它的方式适用于 Angular JS。
回答by Sergio Garcia Alonso
You have to use th:id attribute:
您必须使用 th:id 属性:
<form th:id="'myForm' + ${object.id}" class="some class" th:action="@{/doSomething}" method="post">
// *** Other code here ***
</form>
回答by rgrebski
Here is how you can use dynamic id with label:
以下是如何使用带有标签的动态 ID:
<th:block th:with="randomId=${#strings.randomAlphanumeric(10)}">
<input type="checkbox" th:id="${randomId}">
<label th:for="${randomId}"></label>
</th:block>