我有一个数据表,在其中填充了数据库中的数据。当网页加载时,我调用Bind()函数,该函数用数据填充数据表并初始化数据表。
我还有一个模式弹出窗口,用户可以在其中添加记录。当他们单击“保存”按钮时,它会保存记录,然后我尝试重新填充并重新初始化数据表。
问题是,当我第二次重新初始化数据表时(在按钮上单击),该数据表没有正确地重新初始化。每条记录后都会显示标题(请参见下图)。请注意,这仅在单击按钮时发生。
到目前为止,这是我的代码:
$(document).ready(function () {
var dataTable;
Bind();
function Bind() {
$.ajax({
type: "POST",
url: "Clubs.aspx/GetCustomers",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var customers = xml.find("Table");
var row = $("[id*=gvCustomers] tr:last-child").clone(true);
$("[id*=gvCustomers] tr").not($("[id*=gvCustomers] tr:first-child")).remove();
$.each(customers, function () {
var customer = $(this);
$("td", row).eq(0).html($(this).find("ClubID").text());
$("td", row).eq(1).html($(this).find("ClubName").text());
$("td", row).eq(2).html($(this).find("ClubEmail").text());
$("td", row).eq(3).html("<span>" + $(this).find("ClubID").text() + "</span>");
$("td", row).eq(4).html("<img id='btnID' src='/assets/img/edit.png' Style='width: 20px; height: 18px;'</>");
$("[id*=gvCustomers]").append(row);
row = $("[id*=gvCustomers] tr:last-child").clone(true);
});
//This is where I initializes my datatable
$('table').each(function () {
dataTable = $(this).prepend($("<thead style=background-color:#ff974d></thead>").append($(this).find("tr:eq(0)"))).DataTable({
"responsive": true,
"searching": true,
"aaSorting": [],
"sPaginationType": "full_numbers",
dom: 'lBfrtip',
buttons: [
{
extend: 'copy',
className: 'btn btn-success'
},
{
extend: 'excel',
text: 'Excel',
title: 'Centre Information',
className: 'btn btn-success',
orientation: 'portrait',
exportOptions: {
columns: [0, 1, 2]
}
},
{
extend: 'pdf',
text: 'PDF',
title: 'Centre Information',
className: 'btn btn-success',
orientation: 'portrait',
exportOptions: {
columns: [0, 1, 2]
}
},
{
extend: 'print',
text: 'PRINT',
title: 'Centre Information',
className: 'btn btn-success',
orientation: 'portrait',
exportOptions: {
columns: [0, 1, 2]
}
}
]
});
});
}
});
然后这是保存按钮中的代码,我尝试重新初始化数据表
$("#btnSave").click(function () {
dataTable.destroy();
Bind();
return false;
});
请协助我正确重新初始化数据表。
答案 0 :(得分:0)
尝试将DataTable存储在变量中,并在重新绑定数据之前销毁该变量。
因此,首先创建一个可以在两个函数中访问的变量。
var dataTable;
function Bind() {
//rest of code
}
然后将正确的表分配给变量
dataTable = $(this).prepend($("<thead style=background-color:#ff974d></thead>").append($(this).find("tr:eq(0)"))).DataTable({
然后在该按钮上单击销毁该
$("#btnSave").click(function () {
dataTable.destroy();
Bind();
return false;
});