我正在使用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>
答案 0 :(得分:3)
您可以使用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>');
});
}
&#13;
<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>
&#13;