使用createElemnt在JS中添加多个div

时间:2018-07-09 14:33:10

标签: javascript

这是我的代码:

var div4=document.getElementById('div4'); // get the div element
var div2=document.getElementById('div2'); // create a new div
for (var index = 0; index < array.length; index++) {
    var newDiv=document.createElement("div"); //create a new div
    var newDiv2=document.createElement("div") //create a new div
    newDiv.innerHTML=array[index];
    newDiv.draggable = true;
    newDiv.id = 'record-2-'+index;
    newDiv.className = 'record';
    newDiv2.className = 'record';
    newDiv2.id = 'record-4-'+index;
    newDiv2.draggable = true;
    newDiv2.innerHTML=array[index];
    div4.appendChild(newDiv); // append to div
    div2.appendChild(newDiv2); // append to div
    newDiv.addEventListener("dragstart", handleDragStart);
    newDiv2.addEventListener("dragstart", handleDragStart);
}

如何在没有两个单独的变量 newDiv,newDiv2 的情况下实现相同的功能。

2 个答案:

答案 0 :(得分:0)

您可以克隆div并使用cloneNode()进行添加,因此您要添加两个单独的div,而不是一个相同的div。

var div4=document.getElementById('div4'); // get the div element
var div2=document.getElementById('div2'); // create a new div
for (var index = 0; index < array.length; index++) {
    var newDiv=document.createElement("div"); //create a new div
    newDiv.innerHTML=array[index];
    newDiv.draggable = true;
    newDiv.id = 'record-2-'+index;
    newDiv.className = 'record';

    div4.appendChild(newDiv); // append to div
    newDiv = newDiv.cloneNode(false); // clone the div
    newDiv.id = 'record-4-'+index; // change its id property
    div2.appendChild(newDiv); // append to div
    newDiv.addEventListener("dragstart", handleDragStart);
    newDiv2.addEventListener("dragstart", handleDragStart);
}

答案 1 :(得分:0)

您可以创建一个返回函数或将div添加到传递的div中:

//Required..
function handleDragStart(){};

//Created and append divs
function addDivTo(div, html, id){
    //appendChild() returns the input
    var newDiv = div.appendChild(document.createElement("div")); //create a new div
    newDiv.id = id;
    newDiv.innerHTML = html;
    newDiv.draggable = true;
    newDiv.className = 'record';
    newDiv.addEventListener("dragstart", handleDragStart)
  }

//Some array used below
var array = ['123', '456', '789', 'cucubau'];

var div4 = document.getElementById('div4'); // get the div element
var div2 = document.getElementById('div2'); // create a new div

for (var index = 0; index < array.length; index++) {
  addDivTo(div4, array[index], 'record4-' + index);
  addDivTo(div2, array[index], 'record2-' + index)
}
<div id = 'div4'></div>
<div id = 'div2'></div>