我有一张带有colspans和rowpans的表,就像这个5x3表:
<table id="test">
<tr>
<td colspan="2">1</td><td>2</td><td rowspan="2">3</td><td>4</td>
</tr>
<tr>
<td>5</td><td colspan="2">6</td><td>7</td>
</tr>
<tr>
<td>8</td><td>9</td><td>10</td><td>11</td><td>12</td>
</tr>
</table>
我想在Javascript中创建2D数组,其中包含给定坐标处的单元DOM元素 对于给定的示例,它遵循(为简单起见,数字表示具有相应内容的DOM单元格元素):
[[1, 1, 2, 3, 4], [5, 6, 6, 3, 7], [8, 9, 10, 11, 12]]
你看,它就像Javascript属性table.rows
,但是colspan / rowspan的单元格出现很多次。
如果只允许使用colspan,那么创建这样的数组并不困难 - 只需循环遍历table.rows
并像colspan一样多次推送到数组单元。但是,当允许rowspan时,这变得很棘手。
这是我的尝试:
var tableEl = document.getElementById('test');
var cells2D = [];
var rows = tableEl.rows;
var x = 0, y = 0;
for (var r = 0; r < rows.length; ++r) {
var cells = rows[r].cells;
x = 0;
for (var c = 0; c < cells.length; ++c) {
var cell = cells[c];
var colSpan = x + (cell.colSpan || 1);
var rowSpan = y + (cell.rowSpan || 1);
for (var x2 = x; x2 < colSpan; ++x2) {
for (var y2 = y; y2 < rowSpan; ++y2) {
if (!cells2D[y2]) cells2D[y2] = [];
cells2D[y2][x2] = cell;
}
++x;
}
}
++y;
}
它不适用于示例,但如果我删除最后一列,那么它可以正常工作。
答案 0 :(得分:1)
我需要做同样的事情,但在 C# 中(使用 AngleSharp 库),所以我移植了 Somnium's answer:
static IHtmlTableCellElement[,] GetTableEffectiveCells(IHtmlTableElement table)
{
var rowCount = table.Rows.Length;
var columnCount = table.Rows.Max(row => row.Cells.Length);
var cells = new IHtmlTableCellElement?[rowCount, columnCount];
for (var r = 0; r < rowCount; r++)
{
var x = 0;
foreach (var cell in table.Rows[r].Cells)
{
while (cells[r, x] != null) x++;
var x3 = x + cell.ColumnSpan;
var y3 = r + cell.RowSpan;
for (var y2 = r; y2 < y3; y2++)
for (var x2 = x; x2 < x3; x2++)
cells[y2, x2] = cell;
x = x3;
}
}
return cells!;
}
答案 1 :(得分:0)
我不确定这是否正确,但是我想出了以下代码,例如表格中找到了正确的数组。
var tableEl = document.getElementById('test');
var cells2D = [];
var rows = tableEl.rows;
var rowsLength = rows.length;
for (var r = 0; r < rowsLength; ++r) {
cells2D[r] = [];
}
for (var r = 0; r < rowsLength; ++r) {
var cells = rows[r].cells;
var x = 0;
for (var c = 0, cellsLength = cells.length; c < cellsLength; ++c) {
var cell = cells[c];
while (cells2D[r][x]) {
++x;
}
var x3 = x + (cell.colSpan || 1);
var y3 = r + (cell.rowSpan || 1);
for (var y2 = r; y2 < y3; ++y2) {
for (var x2 = x; x2 < x3; ++x2) {
cells2D[y2][x2] = cell;
}
}
x = x3;
}
}