我需要使用新获取的数据重新初始化jQuery DataTable
。我已经阅读了几篇类似的问题,解决方案包括在重新初始化之前销毁现有的dataTable。该表最初呈现良好,但是当尝试通过更改列数再次呈现它时,出现错误:Uncaught TypeError: Cannot read property 'style' of undefined
。我知道当HTML列计数和DataTables的列定义不匹配时,会发生此错误。这意味着初始表未成功销毁。这是代码:
var dataSet1 = [{
"country": "Benin",
"year": 1996,
"water": 70.0
},{
"country": "Vietnam",
"year": 1996,
"water": 95.1
}];
var dataSet2 = [{
"country": "Benin",
"year": 2000,
"water": 75.8,
"electricity": 58.5 //additional column from the database
},{
"country": "Vietnam",
"year": 2000,
"water": 96.8,
"electricity": 63.2
}];
$('#example_dt').DataTable({
data: dataSet1,
columns: [
{ data: "country" },
{ data: "year" },
{ data: "water" }],
'searching': false
});
$('#update_data_btn').click (function(){
//$("#example_dt").DataTable().fnDestroy();
$('#example_dt').DataTable({
destroy: true,
//retrieve: true
data: dataSet2,
columns: [
{ data: "country" },
{ data: "year" },
{ data: "water" },
{ data: "electricity" }],
// "bDestroy": true,
'searching': false
} );
});
});
我在下面的类似文章中尝试了各种建议,但似乎无法解决。仍然出现相同的错误。
[1] Adding destroy: true
[2] Adding $("#example_dt").DataTable().fnDestroy();
[3] Adding retrieve: true
[4] Adding "bDestroy": true
[5] Using $('#example_dt').empty(); //this empties and new table not created
这里是fiddle