2013-05-11 54 views
0

我想添加id來動態地使用javascript輸入。我該怎麼做。我寫了一個函數,但它不起作用。給元素新標識

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; 
} 
} 

回答

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> 

和類名是在JavaScript中的元素屬性格式,所以你應該使用不同的名稱:

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

FIDDLE

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>