2017-04-01 91 views
0

我正在嘗試使用JavaScript來根據用戶輸入生成一定數量的輸入框。但是,當我使用for循環時,它只生成一個輸入框並在所述輸入框中追加一定的時間。動態生成多個元素

function generateAttributes(){ 
    var y = 1; 
    var mAttributes = document.getElementById('numAttributes').value; 
    var parent = document.getElementsByTagName('div')[17]; 
    var inputBox = document.createElement('input'); 
    inputBox.setAttribute('class', 'form-control'); 
    for(var i = 0; i < mAttributes; i++){ 
     inputBox.setAttribute('id', y); 
     inputBox.setAttribute('placeholder', 'Attribute ' + y); 
     parent.appendChild(inputBox); 
     y++; 
    } 

}

回答

1

你需要爲每個循環迭代創建一個新元素。

移動循環內的以下內容:

var inputBox = document.createElement('input'); 
    inputBox.setAttribute('class', 'form-control'); 

結果:

for(var i = 0; i < mAttributes; i++){ 

    var inputBox = document.createElement('input'); 
    inputBox.setAttribute('class', 'form-control'); 
    inputBox.setAttribute('id', y); 
    inputBox.setAttribute('placeholder', 'Attribute ' + y); 
    parent.appendChild(inputBox); 
    y++; 
} 

您當前正在創建只有一個元素和修改,並在追加相同的元素,在

+0

輝煌,曾!感謝你的幫助! –

+1

@RichardPayne - 如果解決了您的問題,您可以考慮將charlietfl的答案標記爲「已接受」(帶有綠色複選標記)。 – ConnorsFan