JQuery clear HTML table and insert new rows

2020-04-21 05:33发布

问题:

I have been scouting around but cannot find a solution that works.

I have a simple HTML table:

<table id="myTable">
        <thead>
            <tr>
                <th>UserID</th>
                <th>Current Submissions</th>
            </tr>
        <tbody>
            <tr>
            </tr>
        </tbody>
        <thead>
    </table>

using socket.io I am receiving JSON data that I would to append to the table, after clearing it. The code below just deletes the table and doesn't insert the new data?

<script>
    var socket = io();
    socket.on('totalsubmissions', function(msg) {
        $('#myTable').find('tbody').remove();
        // loop over each recevied in the object
        $.each(msg, function(k, v) {
            //display the key and value pair
            var myRow = "<tr><td>" + k + "</td><td>" + v + "</td></tr>";
            $('#myTable').find('tbody').append(myRow);
        });

    });
</script>

Am I removing the table incorrectly?

回答1:

This line is removing the tbody.

$('#myTable').find('tbody').remove();

So when you get to this line:

$('#myTable').find('tbody').append(myRow);

There is no tbody to find.

Change:

$('#myTable').find('tbody').remove();

To:

$('#myTable').find('tbody').empty();