Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

javascript - Create a div using loop

I create a div and its css id like this.

<div id="r1" class="ansbox"></div>
<div id="r2" class="ansbox"></div>
<div id="r3" class="ansbox"></div>
<div id="r4" class="ansbox"></div>
<div id="r5" class="ansbox"></div>
<div id="r6" class="ansbox"></div>
<div id="r7" class="ansbox"></div>
<div id="r8" class="ansbox"></div>
<div id="r9" class="ansbox"></div>
<div id="r10" class="ansbox"></div>

is there a way to create this div using looping statement. Anyone help me..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I would recommend using some javascript (without jquery) for performance:

var toAdd = document.createDocumentFragment();
for(var i=0; i < 11; i++){
   var newDiv = document.createElement('div');
   newDiv.id = 'r'+i;
   newDiv.className = 'ansbox';
   toAdd.appendChild(newDiv);
}

document.appendChild(toAdd);

This way you only make one append(), only 1 reflow, and you don't need jQuery.

To append it to a jQuery selector:

$('sel').append(toAdd);

Or a dom element:

document.getElementById('sel').appendChild(toAdd);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...