在 JavaScript 中,我正在创建一个带有 HTML 表格的网格(您在 Photoshop 中看到的网格类型)。网格大小将是可变的,即可由用户更改,因此必须计算每个网格正方形的大小并除以可用像素数以获得精确大小的网格。
我已经完成了所有这些,但是在添加必要的表格元素来创建网格时遇到了问题。我的代码处于完整的工作状态,除了当我appendChild()
在 for 循环中使用该函数时,它只附加一个子级,而它应该附加到几百个。
我的代码:
grid.show = function(event)
{
var e = event;
if(grid.show_grid == false)
{
grid.show_grid = true;
parent.document.getElementById("grid_table").style.display = "block";
// Get grid (table) and create some elements.
grid.get_grid = parent.document.getElementById("grid_table");
grid.tr = parent.document.createElement("tr");
grid.td = parent.document.createElement("td");
// Clear the grid of all squares so we don't have to worry about subtracting anything.
grid.get_grid.innerHTML = "";
// Calculate the number of horizontal and vertical squares.
var horizontal = Math.ceil(grid.total_width / grid.size);
var vertical = Math.ceil(grid.total_height / grid.size);
// This was a nested loop, removed for demonstration.
// Attempting to add 10 "<tr><td></td></tr>" to the table.
for(var j = 0; j < 10; j++)
{
grid.tr.appendChild(grid.td);
}
//console.log(grid.tr);
// Add the elements to the table.
grid.get_grid.appendChild(grid.tr);
}
else
{
grid.show_grid = false;
parent.document.getElementById("grid_table").style.display = "none";
}
}
这只会返回一个包含单个表数据的表行,如下所示:
<tr>
<td></td>
</tr>
我已经看过这个页面和这个页面,它们听起来很有希望,但我就是不知道如何使它工作。
编辑:代码现在工作,解决方案:
grid.show = function(event)
{
var e = event;
if(grid.show_grid == false)
{
grid.show_grid = true;
parent.document.getElementById("grid_table").style.display = "block";
grid.get_grid = parent.document.getElementById("grid_table");
grid.tr = null;
grid.td = null;
grid.get_grid.innerHTML = "";
var horizontal = Math.ceil(grid.total_width / grid.size);
var vertical = Math.ceil(grid.total_height / grid.size);
for(var i = 0; i < vertical; i++)
{
grid.tr = parent.document.createElement("tr");
for(var j = 0; j < horizontal; j++)
{
grid.td = parent.document.createElement("td");
grid.td.width = grid.size;
grid.td.height = grid.size;
grid.tr.appendChild(grid.td);
}
grid.get_grid.appendChild(grid.tr);
}
}
else
{
grid.show_grid = false;
parent.document.getElementById("grid_table").style.display = "none";
}
}