简体   繁体   English

HTML5动态创建文本框数组并设置文本框的文本

[英]HTML5 Create an array of textboxes dynamically and set text of the text box

I have a div of list of words displayed in textboxes 我在文本框中显示了一个单词列表列表

<div id = "rightbox" ondrop="drop(event)" ondragover="allowDrop(event)">
    <div><input type="text" id="appleword" value="apple" class="textbox" readonly="ture" draggable="true" ondragstart="drag(event)"></div>
    <div><input type="text" id="orangeword" value="orange" class="textbox" readonly="ture" draggable="true" ondragstart="drag(event)"></div>
    <div><input type="text" id="peachword" value="peach" class="textbox" readonly="ture" draggable="true" ondragstart="drag(event)"></div>
</div>

Needs help on creating similar text boxes(in array) dynamically with different values. 需要帮助以不同的值动态创建相似的文本框(数组)。

var words = ['apple', 'orange', 'peach'], // add more to array if needed
    newInputs = document.createDocumentFragment(); // fragment to collect new inputs

// Loop through array of words and generate inputs
words.forEach(function (word) {
    var wrapper = document.createElement('div'),
        fieldSet = document.createElement('fieldset'),
        input = document.createElement('input'); // Inputs default to type=text

    // Decorate elements with needed attributes here (abbreviated)
    wrapper.id = word + 'word';
    input.id = word + 'input';
    input.setAttribute('value', word);
    input.setAttribute('class', 'textbox');
    input.readOnly = true;

    // Nest all these elements and add them to the fragment
    newInputs.appendChild(wrapper).appendChild(fieldSet).appendChild(input);
});

// Insert the fragment into the DOM
document.getElementById('rightbox').appendChild(newInputs)

Adjust code as needed to add missing attributes and event handlers. 根据需要调整代码以添加缺少的属性和事件处理程序。 If you have to support anything older than IE9 change the forEach loop to a for loop. 如果您必须支持IE9之前的版本,请将forEach循环更改为for循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM