js如何自由调整table列的顺序
当前位置:点晴教程→知识管理交流
→『 技术文档交流 』
![]() ![]() <table id="myTable"> <tr> <th>姓名</th> <th>年龄</th> <th>城市</th> </tr> <tr> <td>张三</td> <td>28</td> <td>北京</td> </tr> <!-- 其他行 --> </table>
<script> function reorderColumns(tableId, order) { const table = document.getElementById(tableId); const header = table.querySelector('tr'); const newHeader = header.cloneNode(true); // 复制表头以便重新排序列 const newBody = document.createElement('tbody'); // 创建新的tbody
// 移除原始表头和tbody,以便重新构建 while (table.firstChild) { if (table.firstChild.nodeName === 'TBODY') { table.removeChild(table.firstChild); } else if (table.firstChild.nodeName === 'TR') { break; // 停止在第一个tbody之前的行(通常是表头) } }
// 重新排序表头和内容行 order.forEach(index => { const th = newHeader.children[index]; // 获取新的表头列 newHeader.removeChild(th); // 移除以避免重复添加 header.appendChild(th); // 添加到原始表头中,顺序已改变 // 查找并复制相应的行数据到新tbody中 Array.from(table.querySelectorAll('tr')).forEach(row => { const td = row.children[index]; // 获取相应列的单元格 const newRow = newBody.querySelector(`tr:nth-child(${Array.from(newBody.children).indexOf(row) + 1})`) || document.createElement('tr'); // 获取或创建新行 if (!newBody.contains(newRow)) { // 如果行不存在则添加到新tbody中 newBody.appendChild(newRow); } newRow.appendChild(td); // 添加单元格到新行中 }); }); // 将新表头和新的tbody插入到表格中 table.appendChild(newHeader); table.appendChild(newBody); }
// 示例:将列重新排序为 [2, 0, 1](城市,姓名,年龄) reorderColumns('myTable', [2, 0, 1]); </script> 该文章在 2025/6/23 16:09:07 编辑过 |
关键字查询
相关文章
正在查询... |