当colspan在表格标头单元格中时,数据标签会抛出错误



在我的TH标签中使用colspan时,我会遇到以下错误。

Uncaught TypeError: Cannot read property 'mData' of undefined

通常,当每个行中的表单元格数不相等时,就会发生这种错误,但事实并非如此。这是我的代码:

<table id="foo">
<thead>
    <tr>
        <th colspan="5">asdf</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
    </tr>
</tbody>
</table>
<script>
    $('#foo').DataTable();
</script>

这是Codepen中的一个示例:https://codepen.io/anon/pen/eqovme?editors=1111

使用jQuery 1.12.3和数据表1.10.16

有什么想法?

根据此处的文档,DataTables支持标题中的colspanrowspan,但使用此警告。

每列必须具有一个唯一的单元格,以添加听众。

我想出了一个黑客的解决方法,我不知道它是否是最好的解决方案,但它确实提供了一个有效的解决方案。

创建两个标头行,并使用colspan属性和所有单个列的第二个标头行和第二个标头行。然后应用CSS display: none隐藏行。这将允许DataTable初始化而无需错误。但是,我不确定是否会对其他功能引起任何副作用。

update

最初,我使用CSS应用了display: none,但是该解决方案没有使用容器的完整宽度绘制表。因此,我对此进行了修改,以在表格初始化和绘制表之后将其应用于代码中。这使其可以在完整的容器宽度中显示。

$(document).ready(function() {
  $('#foo').DataTable();
  $("tr.hideme").css({"display" : "none"});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.16/css/jquery.dataTables.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.16/js/jquery.dataTables.min.js"></script>
<table id="foo">
  <thead>
    <tr>
      <th colspan="5">asdf</th>
    </tr>
    <tr class="hideme">
      <th></th>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
    </tr>
  </tbody>
</table>

您只需在表的thead中使用两个TR即可。它与表格中的Colspan和Rowspan通常没有什么不同。您可以在这里看到JSFIDDLE。

<table width="100%" id="example">
  <thead style="background:#C0C0C0;">
    <tr>
      <th colspan="5">first headline</th>
    </tr>
    <tr>
      <th style="padding-left: 15px;"> Id </th>
      <th> Product Name </th>
      <th> Total Events </th>
      <th> Total Revenue </th>
      <th> Rental Time </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Brielle Williamson</td>
      <td>Integration Specialist</td>
      <td>$372,000</td>
      <td>New York</td>
      <td>4804</td>
    </tr>
    <tr>
      <td>Herrod Chandler</td>
      <td>Sales Assistant</td>
      <td>$137,500</td>
      <td>San Francisco</td>
      <td>9608</td>
    </tr>
  </tbody>
</table>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
$(document).ready(function() {
    $('#example').DataTable();
} );

最新更新