繁体   English   中英

我希望我的代码创建由输入行和列数的块组成的网格

[英]I want my code to create grid made of blocks with input amount of rows and columns

我有 2x 数字输入和函数,它应该创建带有 x 行和 y 列的网格,但是当我单击按钮时什么也没有发生。

完整代码:

 var ground = document.getElementById("ground") function getHV() { var x = Number(document.getElementById("h").value); var y = Number(document.getElementById("v").value); for (y; y > 0; y--) { for (x; x > 0; x--) { blocks = "block" + x; blocks = document.createElement("div"); ground.appendChild(blocks); blocks.backgroundcolor = "black"; blocks.style.height = 50 + "px"; blocks.style.width = 50 + "px"; }; } }
 #ground { background-color: lightblue; width:345px; height:450px; }
 <input type="number" id="h" value="10"/> <input type="number" id="v" value="10"/> <button id="submit" onclick="getHV();">Submit</button> <div id="ground"></div>

x 和 y 是字符串。 您需要将它们转换为数字,但是一旦使用x--无论如何它都会转换为数字。

你有一些逻辑问题,但总的来说它是有效的……它们只是不可见的。

 var ground = document.getElementById("ground") function getHV() { let x = Number(document.getElementById("h").value); let y = Number(document.getElementById("v").value); for (y; y > 0; y--) { for (x; x > 0; x--) { const block = document.createElement("div"); block.innerText = "block" + x; block.backgroundcolor = "black"; block.style.height = 50 + "px"; block.style.width = 50 + "px"; ground.appendChild(block); }; } }
 <input type="number" id="h" value="10" /> <input type="number" id="v" value="10" /> <button id="submit" onclick="getHV();">Submit</button> <div id="ground"></div>

1) document.getElementById("h").value返回一个字符串,所以需要将其转换为Number

2) 使用blocks.style.backgroundColor属性设置背景

 <!DOCTYPE html> <html> <head> <style> #ground { background-color: lightblue; width: 345px; height: 450px; } </style> <title>Page Title</title> </head> <body> <input type="number" id="h" value="10"/> <input type="number" id="v" value="10"/> <button id="submit" onclick="getHV();">Submit</button> <div id="ground"></div> <script> var ground = document.getElementById('ground'); function getHV() { var x = Number(document.getElementById('h').value); var y = Number(document.getElementById('v').value); for (y; y > 0; y--) { for (x; x > 0; x--) { blocks = 'block' + x; blocks = document.createElement('div'); ground.appendChild(blocks); blocks.style.backgroundColor = 'black'; blocks.style.height = 50 + 'px'; blocks.style.width = 50 + 'px'; } } } </script> </body> </html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM