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

问题描述 投票:0回答:2

我想在表中删除行时更新索引。对于例如我删除第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);
            }
        }
javascript html rows
2个回答
2
投票

那么你不需要做任何事情!当从dom中删除一行时,会自动更改行索引。

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


0
投票

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

测试它here。只需单击一行即可将其删除。

<!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>
© www.soinside.com 2019 - 2024. All rights reserved.