0

我想使用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;
}
}
4

2 回答 2

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>

并且 className 是 javascript 中的一个元素属性,因此您应该使用不同的名称:

function giveId(cName) {
    var arr = document.getElementsByClassName(cName)
    for (var i = 0; i < arr.length; i++) {
        arr[i].id = "A" + i;
    }
}

小提琴

于 2013-05-11T11:39:06.040 回答
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>
于 2013-05-11T11:36:06.080 回答