动态添加日期作为列标题

时间:2019-02-12 06:39:07

标签: jquery datatable

我想在我的数据表中包含动态列标题和列数据。例如,我有日期选择器,我选择了2019年2月10日至2019年2月12日之间的日期,因此我的数据表将具有

February 10, 2019 |  February 11, 2019 |  February 12, 2019 

作为列标题。如何实现此输出?

这就是我构造数据表的方式

$("#tblClients").DataTable({
  paginate: true,
  pagingType: "full_numbers",
  lengthChange: true,
  filter: true,
  info: true,
  autoWidth: false,
  columnDefs: [{
    autoWidth: true,
    "targets": [1]
  }, {
    "targets": [2, 3, 4, 5],
    "sortable": false
  }],
  "oSearch": {
    "bSmart": false
  },
  "dom": 'Bfrtip',
  "buttons": [{
    "extend": 'excelHtml5',
    "text": 'Download',
    "className": "btn btn-success",
  }],
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" />
<table id="tblClients" class="table table-hover table-bordered">
  <thead>
    <tr>
      <th>No.</th>
      <th>Client</th>
      <th>Name</th>
      <th>Email Address</th>
      <th>No. of Login</th>
      <th>Last Logon Time</th>
    </tr>
  </thead>
  <tbody>
    <?php foreach($logData as $key => $log): ?>
    <tr>
      <td>
        <?php echo $key+1; ?>
      </td>
      <td>
        <?php echo $log['client']; ?>
      </td>
      <td>
        <?php echo $log['name']; ?>
      </td>
      <td>
        <?php echo $log['email']; ?>
      </td>
      <td>
        <?php echo $log['counter']; ?>
      </td>
      <td data-sort="<?php echo $log['created']; ?>">
        <?php
          date_default_timezone_set('Asia/Manila');
          echo date(DATE_FORMAT.' H:i:s', strtotime($log['created']));
        ?>
      </td>
    </tr>
    <?php endforeach; ?>
  </tbody>
</table>

1 个答案:

答案 0 :(得分:1)

您可以使用title选项的columns属性来动态设置数据表头:

// Create a dynamic range of columns
var columns = [];  
for (var i = 1; i <= 5; i++) {      
    var date = new Date(2019,1,i);
    columns.push({
        title: date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear(),
        data: 'dateData_' + i
  });
}

var myTable = $('#example').DataTable({    
    data: dataset,
    columns: columns
});

选中此DEMO