我正在使用 AJAX 通过标题链接对表格列进行排序, 问题是每当我单击链接时,表格都不会重新填充,而是重复行,我想保留标题但清空表格内容, 这是ajax代码:
<script type="text/javascript">
$(document).ready(getData('asc'))
function getData(sort) {
$("#tbl > td").empty();
var srt = sort;
$.ajax({
type: 'GET',
url: '/Book/BooksData?sort=' + srt,
dataTtype: 'json',
success: function (data) {
$.each(data, function (index, val) {
$('#tbl').append('<tr><td>' + val.Title + '</td><td>' + val.Author.Name + '</td></tr>')
});
}
});
}
</script>
HTML:
<table id="tbl" class="table">
<tr>
<th>
<a style="cursor: pointer" onclick="getData('@ViewBag.Sort')" id="sort">Title</a>
</th>
<th>
Author
</th>
<th></th>
</tr>
</table>
在 jQuery 代码中,我还尝试了 tbl
和 tbl>tr
以及 remove
函数
但没有一个有效!
更新:
正如 Zakaria Acharki 在他的回答中所建议的那样,我进行了以下更改:
HTML:
<table id="tbl" class="table">
<thead>
<tr>
<th>
<a style="cursor: pointer" onclick="getData('@ViewBag.Sort')" id="sort">Title</a>
</th>
<th>
Author
</th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
JS:
<script type="text/javascript">
$(document).ready(getData('asc'))
function getData(sort) {
var srt = sort;
$('#tbl>tbody').html('<tr><td>Title</td><td>Author Name</td></tr>'); // why did you add this?
$.ajax({
type: 'GET',
url: '/Book/BooksData?sort=' + srt,
dataTtype: 'json',
success: function (data) {
$.each(data, function (index, val) {
$('#tbl>tbody').html('<tr><td>' + val.Title + '</td><td>' + val.Author.Name + '</td></tr>');
});
}
});
}
</script>
最佳答案
您可以使用 thead/tbody
然后使用 .empty()
删除当前数据并使用 .append()
添加新数据来自 ajax 请求的数据。
HTML :
<table id="tbl" class="table">
<thead>
<tr>
<th>
<a style="cursor: pointer" onclick="getData('@ViewBag.Sort')" id="sort">Title</a>
</th>
<th>
Author
</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
JS :
$('#tbl>tbody').empty();
$.each(data, function (index, val) {
$('#tbl>tbody').append('<tr><td>' + val.Title + '</td><td>' + val.Author.Name + '</td></tr>');
});
希望这对您有所帮助。
$(document).ready(getData('asc'))
function getData(sort) {
$('#tbl>tbody').empty();
var data = {1:'a',2:'b',3:'c'};
$.each(data, function (index, val) {
$('#tbl>tbody').append('<tr><td>Title</td><td>Author Name</td></tr>');
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tbl" class="table">
<thead>
<tr>
<th>
<a style="cursor: pointer" onclick="getData('@ViewBag.Sort')" id="sort">Title</a>
</th>
<th>
Author
</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
关于javascript - 如何清空使用 AJAX 填充的 HTML 表格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41173661/