我有一个显示在文本框中的单词列表
<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>
需要有助于使用不同的值动态创建类似的文本框(在数组中)。
答案 0 :(得分: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的任何内容,请将forEach
循环更改为for
循环。