问题
JavaScript
var textBlock = document.createElement('div');
textBlock.setAttribute('class', 'finalBlock');
var addFinalBlock = document.getElementsByClassName('block')[0];
addFinalBlock.appendChild(textBlock);
textBlock.innerHTML = "Make this block a text block";
// -------
var textBlock2 = document.createElement('div');
textBlock2.setAttribute('class', 'finalBlock');
var addFinalBlock2 = document.getElementsByClassName('block')[0];
addFinalBlock2.appendChild(textBlock2);
textBlock2.innerHTML = "Make this block a text block2";
// -------
var textBlock3 = document.createElement('div');
textBlock3.setAttribute('class', 'finalBlock');
var addFinalBlock3 = document.getElementsByClassName('block')[0];
addFinalBlock3.appendChild(textBlock3);
textBlock3.innerHTML = "Make this block a text block3";
// -------
var textBlock4 = document.createElement('div');
textBlock4.setAttribute('class', 'finalBlock');
var addFinalBlock4 = document.getElementsByClassName('block')[0];
addFinalBlock4.appendChild(textBlock4);
textBlock4.innerHTML = "Make this block a text block4";
I want to create 4 elements with different text. The class needs to remain the same. I think I am doing this with to much code.
Maybe anyone has some information how to make this code look more beautiful and more efficient?
Best wishes and thank you!
回答1:
If you do the same things a lot of times, use a loop. Store the different text in an array and go through it with forEach:
var text = ["text1", "tex2", "text3", "text4"];
text.forEach(function(el) {
var div = document.createElement("div");
div.className = "finalBlock";
div.innerHTML = el;
document.body.appendChild(div);
});
or with a for loop:
var text = ["text1", "tex2", "text3", "text4"];
for(var i = 0; i < text.length; i += 1) {
var div = document.createElement("div");
div.className = "finalBlock";
div.innerHTML = text[i];
document.body.appendChild(div);
}
Demo
回答2:
I believe a better approach will be to only update the DOM once using fragment
.
var docFrag = document.createDocumentFragment();
for(var i = 0; i < divs.length; i++) {
docFrag.appendChild(divs[i]); // Note that this does NOT go to the DOM
}
document.body.appendChild(docFrag); // Appends all divs at once
回答3:
This code will work fine. If you want to add multiple elements on same HTML tag.
var element1= "<br/>"
var element2="<input type='text' />"
var element3= "<br/>"
var onLine = document.getElementById("onLine"); /* This is <ul id="onLine"></ul> */
var on = document.createElement("div");
on.innerHTML = element1+ element3+ element3
on.setAttribute("style", "background-color:rgba(0, 0,
0, 0.3);color:white;border-radius:40px;margin-
bottom:30px;padding: 10px;width: 230px;");
on.appendChild(document.createTextNode('Custom text'));
onLine.appendChild(on);
来源:https://stackoverflow.com/questions/32670902/create-multiple-elements