javascript - 如何从 JQuery AJAX 响应生成的表中删除行?
问题描述
我正在写一段代码,其中:
- 用户输入位置,
- 单击按钮以进行 GET 调用以根据位置检索数据,并且
- 从数据中填充一个表。
每次用户单击按钮时,我都想刷新表格内容,但现在它一直在追加。我想写一个方法,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');
});
});
}
});
解决方案
您需要小心使用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>
推荐阅读
- angular - 将在应用程序引导之前检索到的数据注入到 AppModule 中导入的模块中
- python - 如何在没有互联网/Anaconda(或任何类似免费软件)的 Windows 10 PC 中安装 pandas?
- git - 在所有分支的文件中查找所有出现的文本
- c# - 在 VTK 中从 2D 标签到 3D 空间中的点绘制一条线
- c# - Ini-parser 不读取整个文件
- javascript - 在每次输入更改时提交表单的最佳实践
- ios - Flutter:尝试将 Flutter 应用程序安装到真实 iOS 设备时出现无法安装“Runner”错误
- windows - gcc 找到但未在 Windows git bash 上执行
- php - 如何将数组中的对象值放入字符串
- javascript - React 延迟加载 - 何时使用