2015-06-22 102 views
0

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

<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吗?

在此先感谢。

+0

可能重复递增ID使用jquery](http://stackoverflow.com/questions/7926484/dynamically-create-divs-with-incremented-id-using-jquery) –

+0

@ChaitanyaGadkari谢谢。但有没有可能没有jQuery。像id =“person +'person_id'”。 –

+1

看看[thymeleaf论坛](http://forum.thymeleaf.org/How-to-get-id-values-dynamicaly-td4026516.html),有一个解决方案使用th:每个和一个计数器来设置输入元素的id。 – Guillermo

回答

1

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> 

输出:的[动态创建的div

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 
+0

感谢您的详细解释。 –

+0

Np。顺便说一句,不知道你是否知道,但如果你找到答案或评论有帮助,你可以大拇指。 –