javascript - 如何遍历 html 中的表并使用 javascript 迭代它们的值
问题描述
我正在构建一个网格(20 行和 20 列(正方形)),但努力在表值上循环以实际制作网格
我提供了有关 html 代码的更多信息..
图片在评论中提供
<body>
<h1>Pixel Art Maker</h1>
<h2>Choose Grid Size</h2>
<form id="sizePicker">
Grid Height: <!--- Creating input element to input height --->
<input type="number" id="inputHeight" name="height" min="1" value="1">
Grid Width: <!--- Creating input element to input width --->
<input type="number" id="inputWidth" name="width" min="1" value="1">
<input type="submit">
</form>
<h2>Pick A Color</h2>
<input type="color" id="colorPicker"> <!--- Creating imput element to input a certain color --->
<h2>Design Canvas</h2>
<table id="pixelCanvas"> <tr> <td> </td> </tr> </table>
<!--- Creating the table --->
<script src="designs.js"></script>
</body>
table,
tr,
td {
border: 1px solid black;
}
tr {
height: 20px; //some how this is working as it's the same as
//td when i edit it the td gets edited aswell
width: 20px;
}
td {
height: 20px; //same as here
width: 20px;
}
const lTable = document.querySelector("pixelCanvas");
//Selecting my table and storing it in a variable
let height = document.querySelector("#inputHeight");
//Storing the value on the input height element
let width = document.querySelector("#inputWidth");
//Storing the value of the input width element
function makeGrid() {
//This is the main problem i can't figure out how to iterate the value
// to make the actual grid and give it the event listener
}
解决方案
除非您想向 API 提交数据,否则您不需要表单。
在这里为您的问题找到一个最小的解决方案:
function makeGrid() {
let height = document.querySelector("#inputHeight").value;
//Storing the value on the input height element
let width = document.querySelector("#inputWidth").value;
//Storing the value of the input width element
//Selecting my table and storing it in a variable
const lTable = document.querySelector("#pixelCanvas");
//This is the main problem i can't figure out how to iterate the value
// to make the actual grid and give it the event listener
for (var i=0; i< height;i++) {
var row = lTable.insertRow(i);
for (var j=0; j< width;j++) {
row.insertCell(j);
}
}
}
table {
border: 1px solid black;
}
table td {
border: 1px solid black;
height: 20px;
width: 20px;
}
<div>
<label for="inputHeight">Height</label>
<input type="text" id="inputHeight" value="0"/>
</div>
<div>
<label for="inputWidth">Width</label>
<input type="text" id="inputWidth" value="0"/>
</div>
<input type="submit" value="Draw" onClick="makeGrid()"></input>
<table id="pixelCanvas"></table>
推荐阅读
- java - 如何在 thenAccept 方法中访问 Callable Task 的输入参数?
- python - 获取具有相同 ID 但日期较早的行数
- python - Selenium Python 找到动态更改有时隐藏的下载链接的元素?按钮?
- jquery - 如何为现有类(wordpress)增加更多价值?
- angular - 社交登录问题
- android - 使用实时数据库和 recyclerview 进行大小写敏感搜索
- r - 如何在ggplot中的月度/年度数据上显示十年趋势
- cookies - 为什么将刷新令牌存储在仅 HTTP 的 Cookie 中以防止 CSRF 攻击?
- php - 使用 jAutoCalc 时动态表单插入 SQL php
- javascript - 如何使 onclick 函数与 jquery 一起工作?