1

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

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

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

4

1 回答 1

0
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 更早的任何东西,请将循环更改forEachfor循环。

于 2013-05-20T07:03:28.967 回答