js 实现tr互换
实现表格行互换(tr互换)的方法
在JavaScript中实现表格行(<tr>)互换可以通过操作DOM来完成。以下是几种常见的实现方式:
通过DOM操作交换行
function swapTableRows(tableId, rowIndex1, rowIndex2) {
const table = document.getElementById(tableId);
const rows = table.rows;
if (rowIndex1 >= rows.length || rowIndex2 >= rows.length) return;
const row1 = rows[rowIndex1];
const row2 = rows[rowIndex2];
const temp = document.createElement('tr');
row1.parentNode.insertBefore(temp, row1);
row2.parentNode.insertBefore(row1, row2);
temp.parentNode.insertBefore(row2, temp);
temp.parentNode.removeChild(temp);
}
使用insertBefore方法
function swapRows(row1, row2) {
const tbody = row1.parentNode;
const nextRow = row1.nextSibling === row2 ? row2.nextSibling : row2.nextSibling;
tbody.insertBefore(row1, row2);
tbody.insertBefore(row2, nextRow);
}
使用jQuery实现
如果项目中使用了jQuery,可以更简洁地实现行交换:
function swapRowsJQuery(tableId, rowIndex1, rowIndex2) {
const $table = $('#' + tableId);
const $rows = $table.find('tr');
if (rowIndex1 >= $rows.length || rowIndex2 >= $rows.length) return;
const $row1 = $rows.eq(rowIndex1);
const $row2 = $rows.eq(rowIndex2);
if ($row1.index() < $row2.index()) {
$row2.after($row1);
$row1.after($row2);
} else {
$row1.after($row2);
$row2.after($row1);
}
}
处理事件绑定的注意事项
当交换行时,如果行上有事件监听器,需要注意:
// 在交换行后重新绑定事件
function swapRowsWithEvents(tableId, rowIndex1, rowIndex2) {
swapTableRows(tableId, rowIndex1, rowIndex2);
// 重新绑定事件处理程序
const table = document.getElementById(tableId);
const rows = table.rows;
// 这里添加事件绑定逻辑
// rows[rowIndex1].addEventListener(...);
// rows[rowIndex2].addEventListener(...);
}
完整示例代码
<table id="myTable">
<tr><td>Row 1</td></tr>
<tr><td>Row 2</td></tr>
<tr><td>Row 3</td></tr>
</table>
<button onclick="swapTableRows('myTable', 0, 1)">Swap Row 1 and 2</button>
<script>
function swapTableRows(tableId, rowIndex1, rowIndex2) {
const table = document.getElementById(tableId);
const rows = table.rows;
if (rowIndex1 >= rows.length || rowIndex2 >= rows.length) return;
const row1 = rows[rowIndex1];
const row2 = rows[rowIndex2];
const temp = document.createElement('tr');
row1.parentNode.insertBefore(temp, row1);
row2.parentNode.insertBefore(row1, row2);
temp.parentNode.insertBefore(row2, temp);
temp.parentNode.removeChild(temp);
}
</script>
这些方法提供了不同情况下实现表格行互换的解决方案,可以根据具体需求选择最适合的实现方式。







