如何在使用Javascript删除某一行时更新表

How to update the table when a certain row is deleted using Javascript

本文关键字:一行 更新 删除 Javascript      更新时间:2023-09-26

我想在删除表中的行时更新索引。例如,我删除了第1行,那么第2行和第3行应该变成1行和2行,依此类推

function deleteRow(tableID) {
            try {
            var table = document.getElementById(tableID);
            var rowCount = table.rows.length;
            for(var i=0; i<rowCount; i++) {
                var row = table.rows[i];
                var chkbox = row.cells[0].childNodes[0];
                if(null != chkbox && true == chkbox.checked) {
                    table.deleteRow(i);
                    rowCount--;
                    i--;
                }

            }
            }catch(e) {
                alert(e);
            }
        }

好吧,你什么都不需要做!当从dom中删除一行时,行索引会自动更改。

如果你想仔细检查,你可以挂起一个mutationevent DOMNodeRemoved,看看发生了什么,或者在删除后保留一个断点,并验证行计数和索引。

这里有一个完整的jQuery解决方案:

在这里测试。只需点击一行即可删除。

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js""></script>
    <script>
        $(function () {
            $('tr').click(function () {
                $(this).remove()
                recountRows();
            });

            var recountRows = function () {
                var index = 1;
                $('.index').each(function () {
                    $(this).html(index);
                    index++;
                });
            }

        });
    </script>
</head>
<body>
    <table>
        <tr>
            <td class="index">1</td><td>table text</td>
        </tr>
        <tr>
            <td class="index">2</td><td>table text</td>
        </tr>
        <tr>
            <td class="index">3</td><td>table text</td>
        </tr>
        <tr>
            <td class="index">4</td><td>table text</td>
        </tr>
        <tr>
            <td class="index">5</td><td>table text</td>
        </tr>
        <tr>
            <td class="index">6</td><td>table text</td>
        </tr>
        <tr>
            <td class="index">7</td><td>table text</td>
        </tr>
        <tr>
            <td class="index">8</td><td>table text</td>
        </tr>

    </table>

</body>
</html>