【问题标题】:How do I remove rows from a table I generated from an JQuery AJAX response?如何从 JQuery AJAX 响应生成的表中删除行?
【发布时间】:2018-06-07 02:25:52
【问题描述】:

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

  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');
            });
        });
    }
});

【问题讨论】:

标签: javascript jquery ajax html-table get


【解决方案1】:

您需要小心使用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>

【讨论】:

  • 工作得很好,谢谢!我重新编写了代码以使用回调而不是 async:false,它似乎也解决了我遇到的错误。
猜你喜欢
  • 2012-10-19
  • 2010-11-04
  • 2021-11-11
  • 1970-01-01
  • 1970-01-01
  • 2013-05-23
  • 2014-01-15
  • 2023-03-16
  • 1970-01-01
相关资源
最近更新 更多