本文介绍了考虑到colspan和rowspan,Javascript获取表格单元格二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这个 5x3 表一样的带有 colspans 和 rowspans 的表:

I have a table with colspans and rowspans like this 5x3 table:

<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 中创建二维数组,其中包含给定坐标处的单元格 DOM 元素.
对于给定的示例,它如下(为简单起见,数字表示具有相应内容的 DOM 单元格元素):

I want to create 2D array in Javascript which contains cell DOM elements at given coordinates.
For given example it is following (for simplicity, numbers mean DOM cell elements with corresponding content):

[[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 也被允许时,这会变得棘手.

You see, it is like Javascript property table.rows, but cells with colspan/rowspan appear many times. If only colspan is allowed it is not difficult to create such array - just loop over table.rows and push to array cells as many times as colspan is. However, when rowspan is also allowed, this becomes tricky.

这是我的尝试:

  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;
  }

它不适用于示例,但如果我删除最后一列,则它有效.

It doesn't works on example, but if I remove last column then it works.

推荐答案

我不确定这是否正确,但是我想出了以下代码来找到正确的数组作为示例表.

I'm not sure if this is correct, however I came up with following code which find correct array for example table.

  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;
    }
  }

这篇关于考虑到colspan和rowspan,Javascript获取表格单元格二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 14:11