HTML表格无需选中行上下移、删除后自动重排序实现问题咨询
解决方案
核心调整逻辑
- 移除所有行选中相关代码,操作按钮点击时直接通过DOM关联获取当前所在行,无需提前选中
- 新增全局序号重算方法,在删除行、上下移行操作完成后统一触发,保证所有行序号连续
- 修复原新增行逻辑缺失操作按钮的问题,新增的行自动带上移、下移、删除功能
完整修改后代码
JavaScript 代码
// 删除指定行 function SomeDeleteRowFunction(btn) { var tr = btn.closest('tr'); tr.parentNode.removeChild(tr); // 删除完成后刷新所有行序号 renumberRows(); } // 底部新增IP段行 function addEndIPRanges() { var table = document.getElementById("myTableBody"); var row = table.insertRow(-1); // 插入三个单元格:序号、IP段、操作栏 var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); var cell3 = row.insertCell(2); var rowCount = table.rows.length; cell1.innerHTML = rowCount; cell2.innerHTML = document.getElementById('addIPRange').value; // 给新增行插入操作按钮 cell3.innerHTML = `<button onclick="upNdown('up', this);">↑</button> <button onclick="upNdown('down', this);">↓</button> <input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this)">`; // 清空输入框 document.getElementById('addIPRange').value = ''; } // 行上下移操作 function upNdown(direction, btn) { const tbody = document.querySelector("#myTableBody"); const currentRow = btn.closest('tr'); let targetRow; if (direction === 'up') { targetRow = currentRow.previousElementSibling; if (!targetRow) return; // 已经是首行,无法上移 tbody.insertBefore(currentRow, targetRow); } else { targetRow = currentRow.nextElementSibling; if (!targetRow) return; // 已经是末行,无法下移 tbody.insertBefore(targetRow, currentRow); } // 移动完成后刷新所有行序号 renumberRows(); } // 全局重算所有行序号,保证连续 function renumberRows() { const rows = document.querySelectorAll("#myTableBody tr"); rows.forEach((row, index) => { row.cells[0].textContent = index + 1; }); }
CSS 代码
/* 原选中相关样式不再需要,可以直接删除 */
HTML 代码
<figure class="text-center mb-3"> <h1 class="display-5">IP Range Management</h1> </figure> <hr> <input type='text' id='addIPRange' /> <button style="text-align: center;" onclick="addEndIPRanges()">Add IP Range</button> <hr> <h4 class="iprangetableheader" style="text-align: center;">IP Ranges</h4> <table id="table" style="margin: auto; width: 75%;"> <thead> <tr style="text-align: center;"> <th scope="col">Order</th> <th scope="col">IP Range</th> <th scope="col">Actions</th> </tr> </thead> <tbody id="myTableBody"> <tr> <td>1</td> <td>255.255.255.255</td> <td><button onclick="upNdown('up', this);">↑</button> <button onclick="upNdown('down', this);">↓</button> <input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this)"> </td> </tr> <tr> <td>2</td> <td>234.132.1.642</td> <td><button onclick="upNdown('up', this);">↑</button> <button onclick="upNdown('down', this);">↓</button> <input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this)"> </td> </tr> <tr> <td>3</td> <td>24.32.2.25</td> <td><button onclick="upNdown('up', this);">↑</button> <button onclick="upNdown('down', this);">↓</button> <input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this)"> </td> </tr> </tbody> </table> <hr>
内容的提问来源于stack exchange,提问作者3n6in33r
相关产品推荐
相关产品推荐

