无法破坏()jQuery数据表

时间:2016-07-20 17:32:26

标签: javascript jquery datatables datatables-1.10

我在尝试销毁JQuery数据表时遇到问题。

这是我初始化它的地方:

$(document).ready(function() {
    var table = $(".dynamic-wide-table").DataTable({
        "aaSorting": [],
        "scrollX": true,
        "scrollY": 530,
        "scrollCollapse": true,
        "lengthMenu": [
            [100, 400, 1000, 5000, -1],
            [100, 400, 1000, 5000, "All"]
        ],
        "retrieve": true
    });
});

这是我试图摧毁它的地方:

$(document).ready(function() {  // Note that my page has two tables on it!
    table.destroy();
    table[0].destroy();
});        // Trying to delete both tables first, then just the first table

以下是我的错误:

Uncaught TypeError: table.destroy is not a function
Uncaught TypeError: table[0].destroy is not a function

有人知道发生了什么吗?!我很困惑。

修改

这是我在console.log table时发生的事情的图像。

enter image description here

3 个答案:

答案 0 :(得分:0)

使用each()循环实例化表并将它们存储在数组中:

$(document).ready(function() {
        var tables = [];

    $("table").each(function(i){
     var table = $(this).DataTable({
        "aaSorting": [],
        "scrollX": true,
        "scrollY": 530,
        "scrollCollapse": true,
        "lengthMenu": [
            [100, 400, 1000, 5000, -1],
            [100, 400, 1000, 5000, "All"]
        ],
        "retrieve": true
    });
    tables.push(table);
    });

    $('#button').click( function () {
        // Then you can call destroy on that object
        var elem = tables[0].table().node();
        tables[0].destroy();
        // And empty the element
        $(elem).empty()
    } );
} );

链接到jsFiddle

答案 1 :(得分:0)

您不能同时在platformio.ini内创建和销毁DataTable,因为这些事件是同时触发的。请参阅@ CMedina的JSfiddle,其中显示它们在按下按钮时触发它们。 (假设它们在同一个文件中)忽略这部分;显然他们是不同的文件。

请注意,您在评论中说创建/销毁在不同的文件中。如果确实如此,那么破坏文件如何识别$(document).ready()?如果它不知道DataTable(也可能是由于该页面上不包含脚本文件引起的),那么它将不知道table做了什么,并抛出错误。

修改:我刚刚注意到您正试图在destroy()上使用destroy(),然后在table上使用table[0]。您不能让table成为DataTable,也不能成为DataTable数组。尝试在数组中唯一地命名表或两者;

var table;
table[0] = $('#example').DataTable();
table[1] = $('#example2').DataTable();

或(可能更好)

var table1 = $('#example').DataTable();
var table2 = $('#example').DataTable();

答案 2 :(得分:0)

我认为您的页面中有2个数据表,并且您的初始化适用于所有具有类.dinamyc-wide-table的表。

要仅销毁一个表格,您应该使用tables功能获取页面中的所有数据表。

然后将destroy应用于指定的表:(在我的示例中使用2个数据表)。

$(document).ready(function() {
var table = $(".dynamic-wide-table").DataTable({
    "aaSorting": [],
    "scrollX": true,
    "scrollY": 530,
    "scrollCollapse": true,
    "lengthMenu": [
        [100, 400, 1000, 5000, -1],
        [100, 400, 1000, 5000, "All"]
    ],
    "retrieve": true
});


$('#destroy1').click( function () {
    var dt1 = $.fn.dataTable.tables()[0];
    $(dt1).DataTable().destroy();
} );

$('#destroy2').click( function () {
 var dt2 = $.fn.dataTable.tables()[1];
    $(dt2).DataTable().destroy();
} );
} );

结果: https://jsfiddle.net/cmedina/7kfmyw6x/80/

相关问题