首页 > 解决方案 > 如何从 JQuery AJAX 响应生成的表中删除行?

问题描述

我正在写一段代码,其中:

  1. 用户输入位置,
  2. 单击按钮以进行 GET 调用以根据位置检索数据,并且
  3. 从数据中填充一个表。

每次用户单击按钮时,我都想刷新表格内容,但现在它一直在追加。我想写一个方法,clearTable()但我试过了.remove(),,,等等......没有成功。.parentNode.remove(table)tr:gt(0).remove()

console.log()表明该表在清除时只有一行(表头)。我没有包含我的clearTable()代码,因为我尝试了很多东西但都没有奏效,但我确实展示了我试图调用它的位置。

另外,不确定是否相关,但是虽然我的 GET 调用似乎没有问题地完成,但我的浏览器的开发者控制台显示

尝试加载资源时出错

我在 HTML 正文中的表格代码:

<div class=ui-grid-b">
   <table id="locTable">
       <tr>
           <th>Name</th>
           <th>ID</th>
           <th>Description</th>
       </tr>
   </table>
</div>

Javascript:

$('#loadData').click(function (e) {
    if (getLocationInput() == '') {
        alert("Please enter a location.");
    }
    else {
        // clearTable(); <-- Currently not working
        var locData;
        $.ajax({
            'type': 'GET',
            'url': href,
            'contentType': 'application/json',
            'dataType': 'json',
            headers: { 'Authorization': "Bearer " + getAccessToken() },
            async: false,
            success: function(data) {
                locData = data;
            },
            error: function (xhr, ajaxOptions, thrownError) {
                handleAjaxError(xhr, thrownError);
            }
        });

        // Appends table with values from data
        $(function() {
            $.each(locData.data, function(i, loc) {
                $('<tr>').append(
                $('<td>').text(loc.name),
                $('<td>').text(location.id),
                $('<td>').text(loc.description)).appendTo('#locTable');
            });
        });
    }
});

标签: javascriptjqueryajaxhtml-tableget

解决方案


您需要小心使用locData,因为它是异步给定的。您现在使用它的方式可能不太正确。也就是说,对于您来说,clearTable()我认为您可能会发现这很有帮助。

$("#locTable tr:not(:first-child)").remove();

这是一个演示:

console.log("About to remove childen");

setTimeout(function(){
  $("#locTable tr:not(:first-child)").remove();
  console.log("childen removed");
}, 2 * 1000)
<div class="ui-grid-b">
   <table id="locTable">
       <tr>
           <th>Name</th>
           <th>ID</th>
           <th>Description</th>
       </tr>
       <tr>
           <th>a name</th>
           <th>an ID</th>
           <th>some Description</th>
       </tr>
   </table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


推荐阅读