我想使用javascript动态地添加id到输入。我怎么能这样做。我写了一个函数但它不起作用。
HTML
<form>
element 0_0 <input type = "text" class = "elements"></input>
element 0_1 <input type = "text" class = "elements"></input>
element 1_0 <input type = "text" class = "elements"></input>
element 1_1 <input type = "text" class = "elements"></input>
<input type = "button" onclick = "giveId('elements')"></input>
</form>
的javascript
function giveId(className){
var array = document.getElementsByClassName(className)
for(var i = 0;i < array.length; i++){
array[i].id = "A" + i;
}
}
答案 0 :(得分:1)
输入是自动关闭的:
<form>
element 0_0 <input type="text" class="elements" />
element 0_1 <input type="text" class="elements" />
element 1_0 <input type="text" class="elements" />
element 1_1 <input type="text" class="elements" />
<input type="button" onclick="giveId('elements')" />
</form>
和类Name是javascript中的元素属性,因此您应该使用不同的名称:
function giveId(cName) {
var arr = document.getElementsByClassName(cName)
for (var i = 0; i < arr.length; i++) {
arr[i].id = "A" + i;
}
}
答案 1 :(得分:0)
我测试了你的代码,它工作正常。 您是否尝试过选择新ID?
<form>
element 0_0 <input type = "text" class = "elements"></input>
element 0_1 <input type = "text" class = "elements"></input>
element 1_0 <input type = "text" class = "elements"></input>
element 1_1 <input type = "text" class = "elements"></input>
<input type = "button" onclick = "giveId('elements')"></input>
</form>
<script>
function giveId(classname){
var array = document.getElementsByClassName(classname)
for(var i = 0;i < array.length; i++){
array[i].id = "A" + i;
}
}
</script>