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

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

本文关键字:文本 置文本 数组 动态 创建 HTML5      更新时间:2023-09-26

我有一个文本框中显示的单词列表

<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>

需要帮助动态创建具有不同值的类似文本框(在数组中)

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)

根据需要调整代码以添加缺失的属性和事件处理程序。如果您必须支持比IE9更早的东西,请将forEach循环更改为for循环。