HTML中table转置代码分享
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Transpose Table with Merged Cells</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
padding: 5px;
text-align: center;
}
</style>
</head>
<body>
<table id="originalTable">
<tr>
<th colspan="2">Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Row 1, Col 1</td>
<td>Row 1, Col 2 and 3</td>
<th>Header 3</th>
</tr>
<tr>
<td rowspan="2">Row 2 and 3, Col 1</td>
<td>Row 2, Col 2</td>
<td>Row 2, Col 3</td>
</tr>
<tr>
<td>Row 3, Col 2</td>
<td>Row 3, Col 3</td>
</tr>
</table>
<table id="transposedTable">
</table>
<script>
$(document).ready(function() {
function transposeTableWithMergedCells(tableId) {
var originalTable = $(tableId);
var cellData = [];
var maxCols = 0;
// Collect cell data and calculate the maximum number of columns
originalTable.find('tr').each(function(rowIndex) {
$(this).children('th, td').each(function(cellIndex) {
var rowspan = parseInt($(this).attr('rowspan') || 1);
var colspan = parseInt($(this).attr('colspan') || 1);
// Adjust the starting cell index if necessary
while (cellData[rowIndex] && cellData[rowIndex][cellIndex]) {
cellIndex++;
}
// Store cell data and update colspan and rowspan for the transposed table
for (var i = 0; i < rowspan; i++) {
for (var j = 0; j < colspan; j++) {
if (!cellData[rowIndex + i]) {
cellData[rowIndex + i] = [];
}
cellData[rowIndex + i][cellIndex + j] = {
cell: $(this).clone(),
isOriginal: (i === 0 && j === 0),
rowspan: rowspan,
colspan: colspan
};
}
}
maxCols = Math.max(maxCols, cellIndex + colspan);
});
});
// Create the transposed table
var transposedTable = $('<table></table>');
for (var colIndex = 0; colIndex < maxCols; colIndex++) {
var newRow = $('<tr></tr>');
for (var rowIndex = 0; rowIndex < cellData.length; rowIndex++) {
var cellInfo = cellData[rowIndex][colIndex];
if (cellInfo && cellInfo.isOriginal) {
if (cellInfo.rowspan > 1 || cellInfo.colspan > 1) {
cellInfo.cell.attr('colspan', cellInfo.rowspan);
cellInfo.cell.attr('rowspan', cellInfo.colspan);
}
newRow.append(cellInfo.cell);
} else if (!cellData[rowIndex][colIndex]) {
newRow.append('<td></td>');
}
}
transposedTable.append(newRow);
}
return transposedTable;
}
// Transpose the table and append it to the DOM
var transposedTable = transposeTableWithMergedCells('#originalTable');
$('#transposedTable').append(transposedTable.children());
});
</script>
</body>
</html>