Javascript 动态生成多个元素
我试图使用JavaScript根据用户的输入生成一定数量的输入框。然而,当我使用for循环执行此操作时,它只生成一个输入框,并将所述输入框附加一个设定的时间量Javascript 动态生成多个元素,javascript,jquery,Javascript,Jquery,我试图使用JavaScript根据用户的输入生成一定数量的输入框。然而,当我使用for循环执行此操作时,它只生成一个输入框,并将所述输入框附加一个设定的时间量 function generateAttributes(){ var y = 1; var mAttributes = document.getElementById('numAttributes').value; var parent = document.getElementsByTagName('div')[
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++;
}
函数generateAttributes(){
变量y=1;
var mAttributes=document.getElementById('numAttributes').value;
var parent=document.getElementsByTagName('div')[17];
var inputBox=document.createElement('input');
setAttribute('class','form control');
对于(var i=0;i
}您需要为循环的每个迭代创建一个新元素 在循环内移动以下内容:
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++;
}
for(变量i=0;i
RichardPayne当前只创建一个元素,修改和追加相同的元素@,你可以考虑将查利特夫的答案标记为“接受”(如果使用绿色复选标记),如果它解决了你的问题。