我正在编写一段代码:
每次用户点击按钮时,我都想刷新表格内容,但现在它会不断追加。我想写一个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');
});
});
}
});
答案 0 :(得分:0)
使用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)
&#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;