js 实现tr互换
实现表格行(tr)互换的 JavaScript 方法
方法一:使用 DOM 操作交换行
通过获取表格的行元素(tr)并交换它们的顺序,可以实现行互换。以下是一个示例代码:

function swapTableRows(tableId, rowIndex1, rowIndex2) {
const table = document.getElementById(tableId);
const rows = table.rows;
if (rowIndex1 >= rows.length || rowIndex2 >= rows.length || rowIndex1 < 0 || rowIndex2 < 0) {
console.error('Invalid row indices');
return;
}
const row1 = rows[rowIndex1];
const row2 = rows[rowIndex2];
// 保存行1的HTML
const temp = row1.innerHTML;
// 交换行内容
row1.innerHTML = row2.innerHTML;
row2.innerHTML = temp;
}
方法二:使用 insertBefore 方法交换行
通过 insertBefore 方法可以更高效地交换行的位置,而不需要修改 HTML 内容:

function swapTableRowsWithInsert(tableId, rowIndex1, rowIndex2) {
const table = document.getElementById(tableId);
const rows = table.rows;
if (rowIndex1 >= rows.length || rowIndex2 >= rows.length || rowIndex1 < 0 || rowIndex2 < 0) {
console.error('Invalid row indices');
return;
}
const row1 = rows[rowIndex1];
const row2 = rows[rowIndex2];
// 交换行位置
if (rowIndex1 < rowIndex2) {
table.insertBefore(row2, row1);
} else {
table.insertBefore(row1, row2);
}
}
方法三:使用 jQuery 实现行互换
如果项目中使用了 jQuery,可以通过以下方式实现行互换:
function swapTableRowsWithJQuery(tableId, rowIndex1, rowIndex2) {
const $table = $('#' + tableId);
const $rows = $table.find('tr');
if (rowIndex1 >= $rows.length || rowIndex2 >= $rows.length || rowIndex1 < 0 || rowIndex2 < 0) {
console.error('Invalid row indices');
return;
}
const $row1 = $rows.eq(rowIndex1);
const $row2 = $rows.eq(rowIndex2);
// 交换行位置
if (rowIndex1 < rowIndex2) {
$row2.insertBefore($row1);
} else {
$row1.insertBefore($row2);
}
}
注意事项
- 确保传入的行索引是有效的,避免超出表格的行数范围。
- 如果需要交换的行包含事件监听器或其他动态绑定内容,建议使用方法二或方法三,直接交换 DOM 元素而非 HTML 内容。
- 如果表格是通过动态加载的,确保在 DOM 完全加载后再执行行交换操作。






