如何自定义DataTables中的表格结构?
Hey there! I’ve tinkered with custom DataTables layouts plenty of times, and this rowspan grouping is totally achievable—here’s a hands-on solution that’ll get you the exact structure you’re after:
Core Concept
We’ll leverage DataTables’ createdRow callback to dynamically set the rowspan attribute on the first column’s group header cells, then hide the redundant first-column cells for subsequent rows in the same group.
Step 1: Structure Your Data
First, make sure your dataset includes a grouping identifier (like row1 in your example) so we can group rows together. Here’s a sample:
const tableData = [ { group: "row1", col2: "col2 row11", col3: "col3 row11" }, { group: "row1", col2: "col2 row12", col3: "col3 row12" }, { group: "row2", col2: "col2 row21", col3: "col3 row21" } ];
Step 2: Initialize DataTables with Custom Row Logic
First we’ll count how many rows belong to each group, then use the createdRow hook to apply the rowspan and clean up duplicate cells:
$(document).ready(function() { // Calculate row count per group const groupRowCounts = {}; tableData.forEach(item => { groupRowCounts[item.group] = (groupRowCounts[item.group] || 0) + 1; }); let activeGroup = null; $("#your-table-id").DataTable({ data: tableData, columns: [ { data: "group", title: "col1" }, { data: "col2", title: "col2" }, { data: "col3", title: "col3" } ], createdRow: function(row, data, index) { const currentGroup = data.group; if (currentGroup !== activeGroup) { // New group: set rowspan for the first column cell activeGroup = currentGroup; $(row).find("td").eq(0).attr("rowspan", groupRowCounts[currentGroup]); } else { // Same group: remove the duplicate first-column cell $(row).find("td").eq(0).remove(); } } }); });
Step 3: Polish the Styling (Optional)
To make the grouped cell look clean and vertically centered, add this CSS:
table.dataTable td[rowspan] { vertical-align: middle; border-right: 1px solid #ddd; /* Optional: add a visual divider between group and columns */ }
Quick Edge Case Tips
- If using server-side processing, calculate group row counts on the server and pass that data to the frontend instead of counting client-side.
- If you need sorting/filtering, either disable sorting on the grouped column or add custom logic to preserve groups after sorting.
内容的提问来源于stack exchange,提问作者Random guy

