我的目标是合并表的前3列的行,但是如果第一列有不同的值,我的第二列就不应该合并.

为了更好地直观显示,下面是我当前的表格:

https://imgur.com/uGcr54O

我想让它看起来像这样:

https://imgur.com/8ibuvoU

正如您在第一张图像上看到的,BBB1合并了4次,因为它出现在我的查询4x上,但由于它在第一列中具有不同的值,我需要像在第二张图像上显示的那样合并它.

下面是我当前的代码:

<script>
        var table = document.getElementById('myTable');

        function mergeCells(table, startIndex) {
          let headerCell = null;

          for (let row of table.rows) {
            const firstCell = row.cells[startIndex];

            if (headerCell === null || firstCell.innerText !== headerCell.innerText) {
              headerCell = firstCell;
            } else {
              headerCell.rowSpan++;
              firstCell.remove();
            }
          }
        }
        mergeCells(table, 2);
        mergeCells(table, 1);
        mergeCells(table, 0);
</script>

推荐答案

仅当先前所有列中的相应单元格也已合并时,才能合并一列中的单元格.以下代码递归地工作:在确定了一列中从行M到行N的可合并单元格之后,它调用自身来处理下一列中这些行中的单元格,然后才合并可合并单元格.

function mergeCells(table, startCol, endCol, startRow, endRow) {
  let cell, cellStart;

  function mergeCell(r) {
    if (cell && r > cellStart + 1) {
      if (startCol < endCol)
        mergeCells(table, startCol + 1, endCol, cellStart, r);
      cell.rowSpan = r - cellStart;
      for (let s = cellStart + 1; s < r; s++)
        table.rows[s].cells[startCol].remove();
    }
  }
  for (let r = startRow; r < endRow; r++) {
    const curCell = table.rows[r].cells[startCol];
    if (!cell || cell.textContent !== curCell.textContent) {
      mergeCell(r);
      cell = curCell;
      cellStart = r;
    }
  }
  mergeCell(endRow);
}
const table = document.getElementById('myTable');
mergeCells(table, 0, 2, 1, table.rows.length);
<table id="myTable">
  <tr>
    <th>Column 1</th>
    <th>Column 2</th>
    <th>Column 3</th>
    <th>Column 4</th>
  </tr>
  <tr>
    <td>AAAA</td>
    <td>BBBB</td>
    <td>CCCC</td>
    <td>DDDD</td>
  </tr>
  <tr>
    <td>AAAA</td>
    <td>BBBB</td>
    <td>CCCC</td>
    <td>DDDD</td>
  </tr>
  <tr>
    <td>AAA1</td>
    <td>BBB1</td>
    <td>CCC1</td>
    <td>DDD2</td>
  </tr>
  <tr>
    <td>AAA1</td>
    <td>BBB1</td>
    <td>CCC1</td>
    <td>DDD3</td>
  </tr>
  <tr>
    <td>AAA2</td>
    <td>BBB1</td>
    <td>CCC3</td>
    <td>DDD4</td>
  </tr>
  <tr>
    <td>AAA2</td>
    <td>BBB1</td>
    <td>CCC3</td>
    <td>DDD5</td>
  </tr>
</table>

Javascript相关问答推荐

硬币兑换运行超时

django无法解析余数:[0] from carray[0]'

JQuery. show()工作,但. hide()不工作

如何找出摆线表面上y与x相交的地方?

切换时排序对象数组,切换不起作用

如何从html元素创建树 struct ?

CheckBox作为Vue3中的一个组件

在Three JS中看不到补间不透明度更改效果

在Matter.js中添加从点A到另一个约束的约束

映射类型定义,其中值对应于键

将Node.js包发布到GitHub包-错误ENEEDAUTH

让chart.js饼图中的一个切片变厚?

获取';无法解决导入和导入";slick-carousel/slick/slick-theme.css";';错误

从逗号和破折号分隔的给定字符串中查找所有有效的星期几

WebSocketException:远程方在未完成关闭握手的情况下关闭了WebSocket连接.&#三十九岁;

将范围 Select 器添加到HighChart面积图

为列表中的项目设置动画

ngOnChanges仅在第二次调用时才触发

FindByIdAndUpdate在嵌套对象中创建_id

为什么我的Reaction组件不能使用createBrowserRouter呈现?