数据表明确了

我有一个HTML表,我填写了来自AJAX jQuery调用的数据。这个表使用jQuery插件 – 数据表进行分页,排序等。

从下拉列表更改事件中调用jQuery调用

$("#Dropdownlist").on("change", function () { $.ajax({ type: "POST", url: "@Url.Action("Action", "Controller")", //contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { $.each(data, function (key, item) { $("tbody").append("appending data here"); }); $('#table').dataTable().fnDestroy(); $('#table').dataTable({ "aoColumns": [ { "bSortable": false }, null, null, null, null, null ] }); } }) }); 

这个jQuery已被编辑以缩短它。 这个jQuery工作得很好,它获取数据并将它们添加到新表行中,同时还更新数据表插件以使其适用于新数据。

问题是旧的数据仍然存在,我一直试图用各种各样的东西清理它

 $("#tbodyID tr").detach(); $("#tbodyID tr").remove(); $("#tbodyID").empty(); $("#tbodyID").html(""); $("tbody").empty(); $("tbody").html(""); $('#table').dataTable().fnDraw(false) 

我把它们放在AJAX调用之前。 但是没有一个工作,旧数据仍然存在,每次我调用AJAX调用时,它都会继续用新数据重新填充它,而旧数据仍然存在。

有没有办法用jQuery或内置数据表函数清除tbody?

更新答案以定位dataTables 1.10.x API。 下面使用fnMethods的原始答案是1.9.x,但仍然适用于任何1.9.x – 1.10.x dataTable()

使用返回API实例的DataTable()实例化dataTable时:

 var dataTable = $('#example').DataTable(); 

作为原始答案,完全清空

并插入新行的示例:

 $("#delete").click(function() { dataTable.clear(); dataTable.row.add([ 'new engine', 'new browser', 'new platform', 'new version', 'new css' ]).draw(); }); 

注意draw() 。 当通过API操作表时,必须调用draw()来更新显示以反映这些更改。

演示 – > http://jsfiddle.net/9kLmb9fu/


你应该用

 $('#table').dataTable().fnClearTable(); 

以下是来自jsfiddle的示例,删除

所有内容(在分页表上!)并插入新行:

 $("#delete").click(function() { dataTable.fnClearTable(); dataTable.fnAddData([ 'new engine', 'new browser', 'new platform', 'new version', 'new css' ]); }); 

看小提琴 – > http://jsfiddle.net/yt57V/

您可以使用clear()函数从表中删除所有数据行,如下所示:

 var table = $('#example').DataTable(); table.clear().draw(); 

你可以像这样使用DataTables函数fnClearTable和fnAddData

 $("#Dropdownlist").on("change", function () { $.ajax({ type: "POST", url: "@Url.Action("Action", "Controller")", //contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { var oTable = $('#table').dataTable();//get the DataTable oTable.fnClearTable();//clear the DataTable $.each(data, function (key, item) { oTable.fnAddData(["appending ","data","here"]);//add new row //each element in the array is a td }); /*no need to destroy and create new DataTable $('#table').dataTable().fnDestroy(); $('#table').dataTable({ "aoColumns": [ { "bSortable": false }, null, null, null, null, null ] }); */ } }) }); 

我想你要找的是这段代码:

 var oSettings = $('#table').dataTable().fnSettings(); var iTotalRecords = oSettings.fnRecordsTotal(); for (i=0;i<=iTotalRecords;i++) { $('#table').dataTable().fnDeleteRow(0,null,true); } 

资料来源: http : //www.datatables.net/forums/discussion/comment/15862