如何使用colspan和rowspan结合给定数据集实现HTML表格行列合并
实现方案
核心思路
你需要先对原始数据按text字段分组,统计每个text值对应的行数,给每条数据标记是否需要渲染text列单元格、以及对应的跨行数,渲染表格时通过HTML原生的rowspan属性实现行合并即可。
步骤1:处理原始数据
const groupMap = {} // 按text分组统计行数 this.input.forEach(item => { if (!groupMap[item.text]) { groupMap[item.text] = { count: 0, list: [] } } groupMap[item.text].count += 1 groupMap[item.text].list.push(item) }) // 生成带合并属性的渲染数据 const tableRows = [] Object.values(groupMap).forEach(group => { group.list.forEach((item, idx) => { tableRows.push({ ...item, // 只有分组的第一条数据需要渲染text列 showTextCell: idx === 0, // 跨行数等于当前分组的总条数 textRowSpan: group.count }) }) })
步骤2:渲染HTML表格
原生JS实现示例
<table border="1" cellpadding="8" cellspacing="0"> <thead> <tr> <th>text</th> <th>value</th> <th>desc</th> </tr> </thead> <tbody id="tableTbody"></tbody> </table> <script> const tbody = document.getElementById('tableTbody') tableRows.forEach(row => { const tr = document.createElement('tr') // 渲染text列(仅第一条渲染) if (row.showTextCell) { const textTd = document.createElement('td') textTd.rowSpan = row.textRowSpan textTd.innerText = row.text tr.appendChild(textTd) } // 渲染value、desc列 const valueTd = document.createElement('td') valueTd.innerText = row.value tr.appendChild(valueTd) const descTd = document.createElement('td') descTd.innerText = row.desc tr.appendChild(descTd) tbody.appendChild(tr) }) </script>
Vue框架实现示例
<template> <table border="1" cellpadding="8" cellspacing="0"> <thead> <tr> <th>text</th> <th>value</th> <th>desc</th> </tr> </thead> <tbody> <tr v-for="row in tableRows" :key="row.id"> <td v-if="row.showTextCell" :rowspan="row.textRowSpan">{{ row.text }}</td> <td>{{ row.value }}</td> <td>{{ row.desc }}</td> </tr> </tbody> </table> </template> <script> export default { data() { return { input: [ { id: "1", text: "text 1", value: "value 1", desc: "desc1" }, { id: "2", text: "text 1", value: "value 2", desc: "desc2" }, { id: "3", text: "text 2", value: "value 3", desc: "desc3" } ] } }, computed: { tableRows() { const groupMap = {} this.input.forEach(item => { if (!groupMap[item.text]) { groupMap[item.text] = { count: 0, list: [] } } groupMap[item.text].count += 1 groupMap[item.text].list.push(item) }) const rows = [] Object.values(groupMap).forEach(group => { group.list.forEach((item, idx) => { rows.push({ ...item, showTextCell: idx === 0, textRowSpan: group.count }) }) }) return rows } } } </script>
内容的提问来源于stack exchange,提问作者my trung
相关产品推荐
相关产品推荐

