javascript 如何销毁数据表的第一次初始化(模态内的数据表)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29073255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:03:13  来源:igfitidea点击:

How to destroy first initialization of datatable (DataTable inside a modal)

javascriptjqueryajaxjquery-datatables

提问by d_unknown

I have a modal that displays a table. And I use datatable plugin so that the data is searchable and sortable. It works properly at first but when I close the modal and click other link to the same modal, it displays error. I have found solution to destroy the DataTable and I put the destroy()before the initialization of the datatable but then no data is displayed inside the table.. if I put it after the initialization it gave me the initialization error the second time I click the button. How am I going to solve this?

我有一个显示表格的模式。我使用数据表插件,以便数据可搜索和排序。它起初工作正常,但是当我关闭模态并单击指向同一模态的其他链接时,它显示错误。我找到了销毁数据表的解决方案,destroy()我把它放在数据表初始化之前,但表内没有显示任何数据。我将如何解决这个问题?

here's my code:

这是我的代码:

    $.ajax({
      url: "<?php echo site_url('admin/group/getMember')?>",
      type: 'POST',
      data: { 'groupID': id},
      dataType: 'JSON',
      success: function(result){
        $('#records_table tbody').empty();
        // $('#records_table').DataTable({
            // "bLengthChange": false,
            // "paging":false,
        // });
        $('.modal-header #hdrmsg').text(result[0].fname);
        var trHTML='';

         $.each(result, function (i, item) {
            trHTML += '<tr><td>' + item.fname + '</td><td>' + item.mname + '</td><td>' + item.lname + '</td></tr>';
        });
        $('#records_table tbody').append(trHTML);
        $('#records_table').DataTable({
            "bLengthChange": false,
            "paging":false,
        });
        $('#records_table').DataTable().fnDestroy();

      }

  });

回答by davidkonrad

The main reason for destroying a dataTables instance is if you want to change the initialisation options - like change pagingand so on. Or if the table structure should be altered. None of those circumstances seems to be the case here? To answer the question, the safest way to destroy and reinitialise a table is to use the shorthand option destroy: true:

销毁 dataTables 实例的主要原因是如果您想更改初始化选项 - 如更改paging等。或者如果表结构应该改变。这些情况似乎都不是这里的情况?要回答这个问题,销毁和重新初始化表的最安全方法是使用速记选项destroy: true

var table = $('#records_table').DataTable({
   ...
   destroy : true
});

To go further, I think you are doing it a little backwards.

更进一步,我认为你做得有点倒退。

  • Why empty the table with jQuery $('#records_table tbody').empty();instead of table.clear()?
  • Why inject records with jQuery $('#records_table tbody').append(trHTML);instead of using table.row.add([...])?
  • 为什么用 jQuery$('#records_table tbody').empty();而不是清空表table.clear()
  • 为什么使用 jQuery$('#records_table tbody').append(trHTML);而不是使用注入记录table.row.add([...])

Here is a code scenario similar to the one in the question, which reinitialises the dataTable without conflicts, each time the modal is shown :

这是一个类似于问题中的代码场景,它在每次显示模态时重新初始化数据表而不会发生冲突:

var table;
$('#modal').on('show.bs.modal', function() {
   $.ajax({
      url: url,
      dataType: 'JSON',
      success: function(response) {
         var response = $.parseJSON(response.contents);

         //clear the table, if it exists
         if (table) table.clear();

         //reinitialise the dataTable   
         table = $('#records_table').DataTable({
           destroy: true,
           bLengthChange: false,
           paging: false
         });

         $.each(response, function(i, item) {
           console.log("inserting", item);
           table.row.add([
             item.name,
             item.position
           ]).draw();
         });
       }
    });
});       

see demo -> http://jsfiddle.net/bz958dxj/

看演示 -> http://jsfiddle.net/bz958dxj/

But you really dont need to destroy the table at all, it just slows down performance :

但是你真的根本不需要销毁表,它只会降低性能:

//global table object
table = $('#records_table').DataTable({
   bLengthChange: false,
   paging: false
});

$('#modal').on('show.bs.modal', function() {
   $.ajax({
      url: url,
      dataType: 'JSON',
      success: function(response) {
         var response = $.parseJSON(response.contents);

         //clear the table
         table.clear();

         //insert data 
         $.each(response, function(i, item) {
           console.log("inserting", item);
           table.row.add([
             item.name,
             item.position
           ]).draw();
         });
       }
    });
});   

demo -> http://jsfiddle.net/8mjke9ua/

演示 -> http://jsfiddle.net/8mjke9ua/

NB: I just assumewe are talking about bootstrap modals, based on the reference to .modal-headerin the question.

注意:我只是assume根据问题中的引用谈论引导模式.modal-header

NB2: Notice the $.parseJSON(response.contents), you should do it as you are doing it in the question. The only reason for this is that the examples go trough a proxy to avoid the same-origin policy.

NB2:注意$.parseJSON(response.contents),你应该像你在问题中所做的那样去做。唯一的原因是这些示例通过代理来避免同源策略。