首先,我想要 JavaScript 中的帮助/答案,而不是 jQuery 。
我有一个简单的html表,它有五个属性,其中一个属性中有一个Select对象。我可以在插入新元组时动态添加这些对象,但是当我尝试互相交换两行时会出现问题。
我的行交换功能通过获取当前行并使用当前行下方或上方的行交换内容,具体取决于用户单击的按钮。
交换行功能:
function moveRow(rowId, move) {
var rows = document.getElementById('myTable').rows; // Get the rows from table
var oldRow = rows[rowId].innerHTML; // rowId is the current row that is selected
var newRow = rows[rowId+move].innerHTML; // The new row, either above or under the currently selected one.
if (rowId == 1 && move != 1){ // if the current row is 1, then you cannot swap it with row "0" because it is the table head with the attributes name.
return;
}else{
rows[rowId].innerHTML = newRow; // Swap the new with the old
rows[rowId+move].innerHTML = oldRow; // Swap old with the new.
}
但是当我交换行时,下拉菜单会重置它的原始值(这是列表中的第一个条目)。所以我的问题是你怎么能节省"将前一行的值转换为" new"可以这么说。谢谢!
答案 0 :(得分:1)
问题在于您通过抓取行的innerHTML
属性来“移动”该行,该属性不包括用户已更改的任何状态。相反,移动整个DOM行。
不幸的是,你不能使用rows
数组,因为它是只读的。所以你必须操纵DOM。请注意,这取决于您是一名优秀的开发人员,并使用tbody
标记将表头与表体分开。 :)
<强> (DEMO) 强>
function moveRow(index, direction) {
var rows, rowToMove, pivotRow, tbody;
tbody = document.getElementById('myTable').tBodies[0];
rows = tbody.rows;
// Sanity checking
if (index === 0 && direction === -1) {
return;
}
if (index === rows.length - 1 && direction === 1) {
return;
}
rowToMove = rows[index];
pivotRow = rows[index + direction];
tbody.removeChild(rowToMove);
if (direction === 1) {
tbody.insertBefore(rowToMove, pivotRow.nextSibling);
} else {
tbody.insertBefore(rowToMove, pivotRow);
}
}