如何从我从JQuery AJAX响应生成的表中删除行?

时间:2018-06-06 17:19:40

标签: javascript jquery ajax html-table get

我正在编写一段代码:

  1. 用户输入位置
  2. 点击按钮进行GET调用以根据位置检索数据,
  3. 从数据中填充表格。
  4. 每次用户点击按钮时,我都想刷新表格内容,但现在它会不断追加。我想写一个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');
                });
            });
        }
    });
    

1 个答案:

答案 0 :(得分:0)

使用locData时需要注意,因为它是异步赋值的。你现在使用它的方式可能不太对。也就是说,对于您的clearTable()我认为您可能会觉得这很有帮助。

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

这是一个演示:

&#13;
&#13;
console.log("About to remove childen");

setTimeout(function(){
  $("#locTable tr:not(:first-child)").remove();
  console.log("childen removed");
}, 2 * 1000)
&#13;
<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>
&#13;
&#13;
&#13;