关于jquery:在表头单元格中colspan时DataTables引发错误

DataTables throwing error when colspan in table header cell

在th标签中使用colspan时出现以下错误。

1
Uncaught TypeError: Cannot read property 'mData' of undefined

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<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>


    $('#foo').DataTable();

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

使用jquery 1.12.3和数据表1.10.16

有任何想法吗?


根据此处的文档,数据表在标头中支持colspanrowspan,但要注意这一点。

Each column must have one TH cell which is unique to it for the listeners to be added.

我发现了一个棘手的解决方法,但我不知道这是否是最佳解决方案,但是它确实提供了可行的解决方案。

创建两个标题行,并将第一个标题行与colspan属性一起使用,将第二个标题行与所有单独的列一起使用。然后应用css display: none隐藏该行。这将允许数据表初始化而不会出错。但是,我不确定它是否会对其他功能造成任何副作用。

更新

最初,我使用CSS应用display: none,但此解决方案并未使用容器的整个宽度绘制表格。因此,在表初始化和绘制之后,我对此进行了修改以在代码中应用样式。这样就可以显示整个容器的宽度。

1
2
3
4
$(document).ready(function() {
  $('#foo').DataTable();
  $("tr.hideme").css({"display" :"none"});
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
<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">

<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>


您只需在表的表内使用两个tr即可。与通常在表中使用colspan和rowspan相同。您可以在这里看到jsfiddle。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<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 src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js">

$(document).ready(function() {
    $('#example').DataTable();
} );