我正在尝试使用 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++;
}
}
最佳答案
您需要为循环的每次迭代创建一个新元素。
将以下内容移至循环内:
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++;
}
您当前仅创建一个元素,并一遍又一遍地修改和附加同一元素
关于javascript - 动态生成多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43158843/