javascript - 动态生成多个元素

标签 javascript jquery

我正在尝试使用 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/

相关文章:

javascript - 委托(delegate)uploadfile事件来控制动态加载

javascript - jQuery timpicker 方法内的 Angular2 组件上下文

javascript - 元素在 div 之外的 JS-hover 副作用

javascript - 在 React 教程中,为什么我注释掉 clear fix 后外观没有变化?

javascript - 如何将新行匹配为一个?

javascript - 如何减少 eCharts 的填充?

jquery - 鼠标悬停在菜单上并超时

javascript - 如何从两个数组创建一个迭代数组

javascript - 在 Angular 7 中实现 HTML CSS 和 Javascript 模板

jquery - jquery如何在点击div2时显示一条消息