DataTables“Can not read property”destroy'undefined“ [英] DataTables "Cannot read property 'destroy' of undefined"

查看:398
本文介绍了DataTables“Can not read property”destroy'undefined“的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要创建一个新的DataTable函数。如果一个表已经存在,我希望我的功能销毁现有的表并创建新的表。



我这样做:

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

函数Init_DT(cols,data){

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

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

}

此功能很好地启动我的第一个表,但我得到

解决方案

本地JavaScript变量



一个函数中定义的变量具有局部范围。功能完成时,它被破坏。

  function myFunction(){
var myVar =value;}

该函数myVar在函数完成后将被销毁。在下一次调用中,将再次定义。



使用全局变量。即将其定义在功能之外,然后使用它。
ie

  var myVar ='value'; function myFunction(){//这里myVar可以访问} 

或在函数内部为变量赋值将成为全局变量。

  function myFunction(){myVar ='value'; 

现在myVar也将是全局的。



<因此,您需要使用

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

参考: w3Schools JS Variable Scope


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.

解决方案

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

这篇关于DataTables“Can not read property”destroy'undefined“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆