使用DOM遍历表的问题

Problems with traversing table using DOM

本文关键字:问题 遍历 DOM 使用      更新时间:2023-09-26

我设法解决了使用DOM仅使用JavaScript遍历表行时遇到的一些问题,但遇到了两个障碍。我正在尝试创建一个表,其中每一行都有一组按钮,用于向上、向下或删除特定的行。我能够成功地使用.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>    

您可以使用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);
    }
}

DEMO