我设法解决了一些麻烦,我只使用JavaScript遍历表行,但遇到了2个障碍。我正在尝试创建一个表,其中每一行都有一组按钮,用于向上,向下或移除该特定行。我能够成功使用.replaceChild方法,但它替换了行而不是交换它们。当我尝试.moveRow时,我一直收到错误,说HTML表部分没有该方法。尝试将当前行与下面的行交换时遇到同样的问题。有什么建议吗?
function up(x){
// var tableBody = document.getElementsByTagName("tbody")[0]; // tried it with tableBody and it still didn't work
var table = x.parentNode.parentNode.parentNode;
var tableRow = x.parentNode.parentNode.cloneNode(true);
var previousRow = x.parentNode.parentNode.previousSibling.cloneNode(true);
table.replaceChild(tableRow,x.parentNode.parentNode.previousSibling);
}
function down(x){
var table = x.parentNode.parentNode.parentNode;
var tableRow = x.parentNote.parentNode.cloneNode(true);
var belowRow = x.parentNode.parentNode.nextSibling.cloneNode(true);
table.moveRow(tableRow,x.parentNode.parentNode.nextSibling);
}
我的按钮:
<table id="table1" border="1">
<tbody>
<tr>
<th>Column 1</th> <th>Column 2</th> <th>Column 3</th> <th>Column 4</th>
</tr>
<tr id="enterData">
<td id="buttons">
<input type="button" value="Up" onclick="up(this)" />
<input type="button" value="Down" onclick="down(this)" />
</td>
</tr>
</tbody>
</table>
答案 0 :(得分:1)
您可以使用insertBefore
向上或向下移动行,appendChild
用于最后一行,我也使用* ElementSibling来避免文本节点问题,但这可能会导致相应的问题。
function up(x){
var row = x.parentNode.parentNode;
var table = row.parentNode;
//Don't move up over the header
if (row.previousElementSibling && row.previousElementSibling.previousElementSibling){
table.insertBefore(row,row.previousElementSibling);
}
}
function down(x){
var row = x.parentNode.parentNode;
var table = row.parentNode;
//can't use insertBefore for last row.
if (row.nextElementSibling && row.nextElementSibling.nextElementSibling){
table.insertBefore(row,row.nextElementSibling.nextElementSibling);
}
else{
table.appendChild(row);
}
}