如何用JavaScript为含rowspan的表格插入序号递增的行?
纯JavaScript实现表格行组插入与自动序号递增
需求说明
现有带rowspan属性的表格,需通过按钮触发插入新行组,新行组的序号<th>自动递增,要求使用纯JavaScript实现,不依赖第三方表格库(如jspreadsheet)。
原表格代码
<table class="w-full border "> <caption class="text-start mx-2 text-lg font-semibold"> A. Specify Modules to be developed or modified: </caption> <tbody> <tr> <th rowspan="3" scope="rowgroup" class="border-black border">1</th> <th scope="row" class="border-black border"><input type="text" placeholder="Module Name" class="placeholder:italic font-normal text-xs w-full p-1" /></th> </tr> <tr> <th scope="row" class="border-black border"><input type="text" placeholder="Module Description" class="placeholder:italic font-normal text-xs w-full p-1" /></th> </tr> </tbody> </table>
实现方案
1. 添加触发按钮
在表格下方插入触发按钮:
<button id="addRowGroup" class="mt-3 px-4 py-2 bg-blue-500 text-white rounded">添加新模块组</button>
2. 编写JavaScript逻辑
嵌入以下纯JS代码完成核心功能:
document.getElementById('addRowGroup').addEventListener('click', function() { const tbody = document.querySelector('table tbody'); // 计算当前最大序号 const rowGroupHeaders = tbody.querySelectorAll('th[scope="rowgroup"]'); const lastNum = rowGroupHeaders.length ? parseInt(rowGroupHeaders[rowGroupHeaders.length - 1].textContent) : 0; const newNum = lastNum + 1; // 创建第一行(带序号的行) const row1 = document.createElement('tr'); const numTh = document.createElement('th'); numTh.setAttribute('rowspan', '3'); numTh.setAttribute('scope', 'rowgroup'); numTh.className = 'border-black border'; numTh.textContent = newNum; const nameTh = document.createElement('th'); nameTh.setAttribute('scope', 'row'); nameTh.className = 'border-black border'; const nameInput = document.createElement('input'); nameInput.setAttribute('type', 'text'); nameInput.setAttribute('placeholder', 'Module Name'); nameInput.className = 'placeholder:italic font-normal text-xs w-full p-1'; nameTh.appendChild(nameInput); row1.appendChild(numTh); row1.appendChild(nameTh); // 创建第二行(模块描述行) const row2 = document.createElement('tr'); const descTh = document.createElement('th'); descTh.setAttribute('scope', 'row'); descTh.className = 'border-black border'; const descInput = document.createElement('input'); descInput.setAttribute('type', 'text'); descInput.setAttribute('placeholder', 'Module Description'); descInput.className = 'placeholder:italic font-normal text-xs w-full p-1'; descTh.appendChild(descInput); row2.appendChild(descTh); // 插入新行组到表格末尾 tbody.appendChild(row1); tbody.appendChild(row2); });
关键逻辑说明
- 序号自动递增:通过查询所有
scope="rowgroup"的表头单元格,提取最后一个序号并加1,得到新行组的序号。 - 行组结构复用:完全复刻原表格的行组结构,包括
rowspan属性、样式类和输入框配置,保证视觉一致性。 - 无依赖实现:全程使用原生DOM API,不引入任何第三方库。
内容的提问来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

