如何使DataTable仅在所有内容渲染后显示

时间:2019-04-12 16:57:56

标签: javascript jquery datatables

我刚开始使用js,并为DataTable开发了此代码

$(document).ready(function() {
  var table = $('#T_coin_list').DataTable({
    dom: 'Blfrtip',
    iDisplayLength: 100,
    lengthMenu: [
      [50, 100, -1],
      [50, 100, "All"]
    ],
    order: [
      [4, "desc"]
    ],
    buttons: [
      'copyHtml5',
      'excelHtml5',
      'csvHtml5',
      'pdfHtml5'
    ],
    columnDefs: [{
        targets: [0, 1],
        className: 'dt-head-left'
      },
      {
        targets: [2, 3, 4, 5, 6, 7, 8],
        className: 'dt-head-center'
      },
      {
        targets: [2, 3],
        className: 'dt-body-center'
      },
      {
        targets: 0,
        data: "Logo",
        render: function(data, type, row) {
          return '<img src="' + data + '" height="30" width="30" />';
        }
      },
      {
        width: "3%",
        targets: 0
      },
      {
        width: "15%",
        targets: 1
      },
      {
        width: "7%",
        targets: 2
      },
      {
        width: "10%",
        targets: [3, 4, 5, 6, 7, 8]
      },
      {
        targets: 0,
        searchable: false,
        orderable: false
      },
      {
        type: "natural",
        targets: [3, 4, 5, 6, 7, 8]
      }

    ]
  });

  $(table.column(0).header()).text('');



  function replaceNans(item, index) {
    table.column(item).nodes().each(function(node, index, dt) {
      if (table.cell(node).data() == 'nan') {
        table.cell(node).data('---------------');
      }
    });
  }

  var numbers = [4, 5, 6, 7, 8];
  numbers.forEach(replaceNans)


  $($.fn.dataTable.tables(true)).DataTable()
    .columns.adjust();

});

这很好用,但是事实是,当打开页面时,DataTable显示为原始,而没有呈现/格式化。例如,对于徽标列,我将其定义为:

{
  targets: 0,
  data: "Logo",
  render: function(data, type, row) {
  return '<img src="'+data+'" height="30" width="30" />'; }
},

页面打开时,它仍在每个单元格中显示url文本-而不是已渲染的图像。如何使表格仅在所有用于渲染/格式化的js代码运行完毕后才显示?

2 个答案:

答案 0 :(得分:1)

也可以在他们的实际样本中看到相同的问题。一种方法可能是在html本身的初始负载下隐藏表格,如下所示,

<table id="T_coin_list" style="display:none" border="0" class="display cell-border nowrap compact">

在fnPreDrawCallback上显示进度,显示进度并在init完成后将其隐藏,并在该事件本身上显示实际表以获取更好的体验。

"fnPreDrawCallback":function(){
  $("#progress").show();
  //alert("Pre Draw");
},
"fnInitComplete":function(){
  $("#T_coin_list").show();
  $("#progress").hide();
  //alert("Completed");
}

希望有帮助。

答案 1 :(得分:0)

您可以隐藏使用

$("#T_coin_list").hide(); 

渲染时。或以其他方式将其隐藏。

然后

$("#T_coin_list").show(); 

渲染img后