後台報表、數據展示頁常需將連續相同數據的儲存格合併(rowspan/colspan),減少視覺噪音。本文提供兩個通用函式:單列行合併與多列層級合併,支援任意列數、動態數據。
/**
* 表格指定列合併相同值的相鄰儲存格
* @param {HTMLTableElement} table - 表格 DOM
* @param {number} colIndex - 要合併的列索引(0-based)
*/
function mergeCellsVertically(table, colIndex) {
const rows = table.rows;
let startRow = 0;
let count = 1;
let prevValue = null;
for (let i = 0; i < rows.length; i++) {
const cell = rows[i].cells[colIndex];
const currValue = cell.innerText.trim();
if (currValue === prevValue) {
count++;
cell.style.display = 'none'; // 隱藏被合併的儲存格
} else {
// 結束上一組,設定 rowspan
if (count > 1) {
rows[startRow].cells[colIndex].rowSpan = count;
}
// 開始新組
startRow = i;
count = 1;
prevValue = currValue;
}
}
// 處理最後一組
if (count > 1) {
rows[startRow].cells[colIndex].rowSpan = count;
}
}
例如:第 0 列合併後,第 1 列僅在同一主分組內合併。
/**
* 多列層級合併
* @param {HTMLTableElement} table
* @param {number[]} colIndices - 列索引陣列,按優先級排序 [主列, 從列, ...]
*/
function mergeCellsHierarchical(table, colIndices) {
const rows = table.rows;
const groups = []; // {start, end, values[]}
// 先按第 0 列分組
let start = 0;
for (let i = 1; i <= rows.length; i++) {
const val0 = rows[i]?.cells[colIndices[0]]?.innerText.trim();
const val0Prev = rows[i-1].cells[colIndices[0]].innerText.trim();
if (i === rows.length || val0 !== val0Prev) {
groups.push({ start, end: i - 1, level: 0 });
start = i;
}
}
// 遞歸處理後續列
function processLevel(groups, level) {
if (level >= colIndices.length) return;
const col = colIndices[level];
const newGroups = [];
for (const g of groups) {
let subStart = g.start;
let subCount = 1;
let prevVal = rows[g.start].cells[col].innerText.trim();
for (let i = g.start + 1; i <= g.end; i++) {
const currVal = rows[i].cells[col].innerText.trim();
if (currVal === prevVal) {
subCount++;
rows[i].cells[col].style.display = 'none';
} else {
if (subCount > 1) {
rows[subStart].cells[col].rowSpan = subCount;
}
subStart = i;
subCount = 1;
prevVal = currVal;
}
}
if (subCount > 1) {
rows[subStart].cells[col].rowSpan = subCount;
}
// 記錄子分組供下一層級使用
// 這裡簡化:實際需按 subStart/subCount 切分
}
}
processLevel(groups, 1);
}
<table id="dataTable" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr><th>部門</th><th>組別</th><th>姓名</th><th>薪資</th></tr>
</thead>
<tbody>
<tr><td>技術部</td><td>前端組</td><td>張三</td><td>15000</td></tr>
<tr><td>技術部</td><td>前端組</td><td>李四</td><td>14000</td></tr>
<tr><td>技術部</td><td>後端組</td><td>王五</td><td>16000</td></tr>
<tr><td>市場部</td><td>推廣組</td><td>趙六</td><td>12000</td></tr>
<tr><td>市場部</td><td>推廣組</td><td>孫七</td><td>11000</td></tr>
</tbody>
</table>
<script>
window.onload = function () {
const table = document.getElementById('dataTable');
// 合併第 0 列(部門)、第 1 列(組別)
mergeCellsVertically(table, 0);
mergeCellsHierarchical(table, [0, 1]); // 或分別呼叫並處理層級邏輯
};
</script>
/* 隱藏被合併的儲存格 */
td[style*="display: none"] { display: none !important; }
/* 合併儲存格垂直置中 */
td[rowspan] { vertical-align: middle; }
/* 表格邊框合併 */
table { border-collapse: collapse; }
th, td { border: 1px solid #ddd; }
async function renderAndMerge() {
const data = await fetch('/api/report').then(r => r.json());
const tbody = document.querySelector('#dataTable tbody');
tbody.innerHTML = data.map(row => `
${row.dept}
${row.group}
${row.name}
${row.salary}
`).join('');
// 渲染完成後執行合併
mergeCellsVertically(document.getElementById('dataTable'), 0);
mergeCellsVertically(document.getElementById('dataTable'), 1);
}
tbody 內 td。display:none 而非 deleteCell(),保持 DOM 索引穩定,利於後續操作。rowSpan = 1、style.display = '' 重置,再重新合併。rowSpan 屬性名區分大小寫,統一用 rowSpan(JS 屬性)而非 rowspan(HTML 屬性)。表格合併本質是「連續相同值分組 + 設定 rowspan + 隱藏多餘儲存格」。掌握核心邏輯後,可輕鬆擴展至多級合併、跨表格同步、導出 Excel 保持合併等進階需求。