html table动态合并单元格 js方法

时间:2021-02-05 09:07:49
<script>
$(document).ready(function(){
function mc(tableId, startRow, endRow, col) {
var tb = document.getElementById(tableId);
if (col >= tb.rows[0].cells.length) {
return;
}
if (col == 0) { endRow = tb.rows.length-1; }
for (var i = startRow; i < endRow; i++) {
if (tb.rows[startRow].cells[col].innerHTML == tb.rows[i + 1].cells[0].innerHTML) {
tb.rows[i + 1].removeChild(tb.rows[i + 1].cells[0]);
tb.rows[startRow].cells[col].rowSpan = (tb.rows[startRow].cells[col].rowSpan | 0) + 1;
if (i == endRow - 1 && startRow != endRow) {
mc(tableId, startRow, endRow, col + 1);
}
} else {
mc(tableId, startRow, i + 0, col + 1);
startRow = i + 1;
}
}
}
mc('table1',0,0,0);
})
</script>