【问题标题】:DataTables throwing error when colspan in table header cell表格标题单元格中的colspan时DataTables抛出错误
【发布时间】:2018-08-06 11:42:03
【问题描述】:
在我的 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
有什么想法吗?
【问题讨论】:
标签:
jquery
html-table
datatables
【解决方案1】:
根据文档 here,Datatables 支持标头中的 colspan 和 rowspan,但有此警告。
每一列必须有一个唯一的 TH 单元格,以便添加侦听器。
我想出了一个老套的解决方法,我不知道它是否是最好的解决方案,但它确实提供了一个可行的解决方案。
创建两个标题行,并使用具有colspan 属性的第一个标题行和包含所有单独列的第二个标题行。然后应用 css display: none 隐藏该行。这将允许数据表初始化而不会出错。但是,我不确定它是否会对其他功能造成任何副作用。
更新
最初我使用 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>
【解决方案2】:
你可以简单地在表格的头内使用两个 tr 。它与通常在表中使用 colspan 和 rowspan 没有什么不同。你可以看到jsfiddle here.
<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();
} );