使用for循环打印出多个div

时间:2019-02-06 00:19:20

标签: javascript html

我正在尝试创建一个程序,该程序可以打印100平方格(使用循环),每个div具有不同的随机背景色。

它经历了循环,因为它找到了100种不同的颜色(在控制台中) 但这只能使一个正方形。

HTML:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>That's a Lot of Div</title>
</head>

<body>
    <div id="box" ></div>
    <script src="app.js"></script>
</body>
</html>

JS:

for (var i=0; i<100; i++) {
    let box = document.querySelector("#box");
    box.style.float = "left";
    box.style.height = "50px";
    box.style.width = "50px";
    box.style.backgroundColor = randomColor();
    console.log(box.style.backgroundColor);
}


function randomColor() {
    var r = Math.round( Math.random() * 255);
    var g = Math.round( Math.random() * 255);
    var b = Math.round( Math.random() * 255);
    var colorString = "rgb(" + r + "," + g + "," + b + ")";
    return colorString;
}

它打印一个单一的div方块,每次刷新页面时都会改变颜色,而不是100 div的方块。

2 个答案:

答案 0 :(得分:1)

Lauren,请参见下文,对创建元素进行一些更改。

请注意,我们(async function() { const myArray = ["one", "two", "three", "four"]; for(let i = 0; i < myArray.length; i++) { const result = await myAsyncFunction(myArray[i]); // ^^^^^ if (result) { // do something } else { i--; } } })(); 和我们appendChild。每个createElement是一个对象,必须创建。

div
for (var i=0; i<100; i++) {
    // We need something to add our new element too
    let target = document.querySelector("#target");
    // Now we have to create a NEW element
    let box = document.createElement('div');
    // Removed the float for the answer as they will stack on top other wise.
    //box.style.float = "left";
    box.style.height = "50px";
    box.style.width = "50px";
    box.style.backgroundColor = randomColor();
    // Now we add it to our target
    target.appendChild(box); 
}


function randomColor() {
    var r = Math.round( Math.random() * 255);
    var g = Math.round( Math.random() * 255);
    var b = Math.round( Math.random() * 255);
    var colorString = "rgb(" + r + "," + g + "," + b + ")";
    return colorString;
}

答案 1 :(得分:0)

var n = prompt("Enter the number");

for (var i = 0; i < n; i++) {
  
    let target = document.querySelector("#target");
    
    let box = document.createElement('div');
  
    box.style.float = "left";
    box.style.height = "50px";
    box.style.width = "50px";
    box.style.marginLeft="20px";
    box.style.backgroundColor ="red";
   
    target.appendChild(box); 
}