向数据表中添加额外的列

时间:2016-09-19 09:19:13

标签: javascript datatables

我需要将列(标题)添加到数据表中。在示例中,我对期间进行了过滤,如果我选择从2016年1月到2016年5月的期间,那么我需要像这样添加列<th>

Buyer|January 2016 | February 2016 | April 2016 | May 2016 | 

但是当我从2016年1月到2016年6月选择期间时

Buyer|January 2016 | February 2016 | April 2016 | May 2016 | June 2016

任何想法???我正在使用DataTables。

1 个答案:

答案 0 :(得分:0)

您可以使用类似于此drawDataTable的函数,将月份包装在数组中,清除标题行,最后添加标题。

&#13;
&#13;
(function() {
  var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  var sel1 = document.querySelector('#sel1');
  var sel2 = document.querySelector('#sel2');
  var year = 2016;
  var table = document.querySelector('table');

  function fillMonths(month, select) {
    var element = document.createElement('option');
    element.textContent = month;
    select.appendChild(element);
  }

  months.forEach(function(month) {
    fillMonths(month, sel1);
  });
  months.forEach(function(month) {
    fillMonths(month, sel2);
  });

  function drawDataTable(selected) {
    var rest = months.slice(months.indexOf(selected[0]), months.indexOf(selected[1]) + 1);
    var nodes = table.rows[0];

    while (nodes.children.length > 1) {
      var cell = nodes.children[1];
      nodes.removeChild(cell);
    }

    rest.forEach(function(month) {
      var header = document.createElement('th');
      header.textContent = month + ' ' + year;
      table.rows[0].appendChild(header);
    });
  }

  var monthSelected = ['January', 'January'];
  drawDataTable(monthSelected);

  sel1.addEventListener('change', function(event) {
    monthSelected[0] = event.target.value;
    drawDataTable(monthSelected);
  });

  sel2.addEventListener('change', function(event) {
    monthSelected[1] = event.target.value;
    drawDataTable(monthSelected);
  });
})();
&#13;
body {
  font-family: "Open Sans", sans-serif;
}
table {
  border-collapse: collapse;
}
th {
  border: 2px solid black;
}
&#13;
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Made with Thimble</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>

  <h1>Choose date</h1>
  Month
  <select id="sel1"></select>
  to
  <select id="sel2"></select>
  <table>
    <tr>
      <th>Buyer</th>
    </tr>
  </table>
  <script src="script.js"></script>
</body>

</html>
&#13;
&#13;
&#13;