DataTables “Cannot read property 'destroy'

2019-08-08 11:41发布

问题:

I want to make a function to create a new DataTable. If a table already exists, I would like my function destroy the existing table and create the new one.

I did this:

$.ajax().done(function(response){
            Init_DT(response['cols'], response['data']);
        });

function Init_DT(cols, data){

        if($('#mytable tr').length > 0){
            table.destroy();
        }

        var table = $('#mytable').DataTable({
            "data": data,
            "columns": cols
        });

    }

This function works well to initiate my first table but I get "Cannot read property 'destroy' of undefined" on subsequent calls.

回答1:

Local JavaScript Variables.

a variable defined inside a function has a Local Scope. It is destroyed when function finishes.

function myFunction() {
var myVar = "value";}

this function myVar will be destroyed after the function has done its work. in the next call it will be defined again.

Use global variable. i.e define it outside the function and then use it. i.e

var myVar='value';function myFunction(){//here myVar can be accessed}

or inside your function assign a value to a variable it will become global.

function myFunction(){ myVar = 'value'; }

now myVar will also be global.

Therefore you need to use

table = $('#mytable').DataTable({
            "data": data,
            "columns": cols
        });

reference: w3Schools JS Variable Scope