/**
* 合并表格中相同数据的行和列
* @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列相同数据