如何在HTML5 + Thymeleaf中分配动态ID

时间:2015-06-22 04:05:42

标签: html5 thymeleaf

HTML

<form id="searchPersonForm" action="#" th:object="${person}" method="post">
<input type="text" class="form-control" id="person_id" th:field="*{person_id}"></input>
<input type="text" class="form-control" id="child_id" th:field="*{child_id}"></input>
</form>

如何分配动态ID,如person_id_100,person_id_200 ...和child_id_100,child_id_200 ......值100,200是实际的person_ids。

我们可以不用jQuery吗?

提前致谢。

1 个答案:

答案 0 :(得分:1)

如果你打算认真对待jQuery,那么jQuery可能值得学习,但这可以用一个简单的javascript文件来完成:

//saved as javascript.js

var formId = "searchPersonForm";
var inputArray = [];
for(var x=0;x < 10;x++){
    var newId = x*100
    var newInput = document.createElement("input")
    newInput.id = "person_id_" + newId
    inputArray.push(newInput);
}
for(var x=0;x < inputArray.length;x++){
    document.getElementById(formId).appendChild(inputArray[x])
    console.log(inputArray[x].id)
}

在表单实例化后的某个时刻,只需在页面中包含脚本:

<html>
<head>
</head>
<body>
<form id="searchPersonForm" action="#" th:object="${person}" method="post">
<input type="text" class="form-control" id="person_id" th:field="*{person_id}"></input>
<input type="text" class="form-control" id="child_id" th:field="*{child_id}"></input>
<script src="javascript.js"></script>
</form>
</body>

输出:

person_id_0
javascript.js:11 person_id_100
javascript.js:11 person_id_200
javascript.js:11 person_id_300
javascript.js:11 person_id_400
javascript.js:11 person_id_500
javascript.js:11 person_id_600
javascript.js:11 person_id_700
javascript.js:11 person_id_800
javascript.js:11 person_id_900