2013-05-20 100 views
1

我在文本框中顯示的單詞的列表中使用不同的值一個divHTML5創建動態文本框的數組,並設置文本框的文本

<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
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循環。

+0

thx非常多,以及如何使字可拖動+呼叫拖曳(事件) – user2400583

+0

nvm我已經計算出了alr,thx – user2400583