2025-07-15 jquery 动态合并行列表格单元格

/**

* 合并表格中相同数据的行和列

* @param {string} tableSelector 表格选择器

* @param {number} compareCols 需要比较的列数(默认全部列)

*/

function mergeTableCells(tableSelector, compareCols,lie) {

const $table = $(tableSelector);

  const rows = $table.find('tr');

  const colsToCompare = compareCols || $table.find('tr:first th').length;

  // 行合并(垂直方向)

  for (let col =0; col < lie; col++) {

let prevValue =null;

    let startRow =0;

    rows.each(function(rowIndex) {

const cell = $(this).find('th').eq(col);

      const currentValue = cell.text().trim();

      if (currentValue === prevValue) {

cell.hide();

        $(rows[startRow]).find('th').eq(col).attr('rowspan', rowIndex - startRow +1);

      }else {

startRow = rowIndex;

        prevValue = currentValue;

      }

});

  }

// 列合并(水平方向)

  rows.each(function() {

const cells = $(this).find('th');

    let prevValue =null;

    let startCol =0;

    cells.each(function(colIndex) {

if (colIndex >= colsToCompare)return;

      const currentValue = $(this).text().trim();

      if (currentValue === prevValue) {

$(this).hide();

        $(cells[startCol]).attr('colspan', colIndex - startCol +1);

      }else {

startCol = colIndex;

        prevValue = currentValue;

      }

});

  });

}

mergeTableCells('#table_left', 4,2); // 合并前4列相同数据

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容