How to destroy a datatable?

2020-05-18 17:15发布

I'm using datatables and using bootstrap-daterangepicker to select a range for which data will be shown in Datatables.

It is working fine.

The problem is when I select a new range in daterangepicker, it provides me with a callback function where I can do my stuff. In that callback function, I'm calling Datatables again. But since the table is already being created, how can I destroy the previous table and show a new one in it's place?

Kindly help. I'm stuck. :(

EDIT: I've the following code:

$(element).daterangepicker({options},
function (startDate, endDate) { //This is the callback function that will get called each time
$('#feedback-datatable').dataTable({
                        "sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
                        "sPaginationType": "bootstrap",
                        "oLanguage": {
                            "sLengthMenu": "_MENU_ records per page",
                            "oPaginate": {
                                "sPrevious": "Prev",
                                "sNext": "Next"
                            }
                        },
                        "aoColumnDefs": [{
                            'bSortable': false,
                            'aTargets': [2,4]
                        }],
                        "bAutoWidth": false,
                        "aoColumns": [
                                      {"sWidth": "20%"},
                                      {"sWidth": "15%"},
                                      {"sWidth": "45%"},
                                      {"sWidth": "15%"},
                                      {"sWidth": "5%"}
                                      ]
                    });
}

8条回答
▲ chillily
2楼-- · 2020-05-18 17:37

I know this is an old question, but since I bumped into a similar issue and resolved it.

The following should do the trick (the comments are coming from the DataTable API doc).

// Quickly and simply clear a table
$('#feedback-datatable').dataTable().fnClearTable();

// Restore the table to it's original state in the DOM by removing all of DataTables enhancements, alterations to the DOM structure of the table and event listeners
$('#feedback-datatable').dataTable().fnDestroy();
查看更多
Rolldiameter
3楼-- · 2020-05-18 17:38

To completely delete and remove the datatable object with its DOM elements you need to :

//Delete the datable object first
if(oTable != null)oTable.fnDestroy();
//Remove all the DOM elements
$('#feedback-datatable').empty();
查看更多
登录 后发表回答