使用GetUiKit和Datatables实现可排序分组表头的正确方法
搞定UIKit + DataTables 分组表头排序问题
嘿,我知道你现在遇到的问题了——多层表头带colspan的时候,DataTables没法自动识别所有可排序的表头,导致只有部分表头能点击排序。别担心,咱们只需要给DataTables加一点配置,就能让所有表头都能触发排序啦!
问题根源
你的代码里第二层表头的comment用了colspan="2",这打乱了DataTables默认的表头-列映射逻辑。它不知道update date对应哪一列,也没法把跨列的表头和具体数据列关联起来,所以才会出现点不动的情况。
修正后的完整代码
<html> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.2/css/uikit.min.css"> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.uikit.min.css"> <script src="https://code.jquery.com/jquery-3.3.1.js"></script> <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.10.19/js/dataTables.uikit.min.js"></script> </head> <body> <table id="example" class="uk-table uk-table-hover uk-table-striped" style="width:100%"> <thead> <tr> <th>creating date</th> <th>name</th> <th>location</th> </tr> <tr> <th>update date</th> <th colspan="2">comment</th> </tr> </thead> <tbody> <tr> <td>20180901</td> <td>john</td> <td>paris</td> </tr> <tr> <td>20190901</td> <td colspan="2">bblbablbalbal</td> </tr> <tr> <td>20180902</td> <td>may</td> <td>london</td> </tr> <tr> <td>20190902</td> <td colspan="2">bblbablbalbal</td> </tr> </tbody> </table> <script> $(document).ready(function() { $('#example').DataTable({ // 核心配置:给每一列指定对应的表头单元格 columnDefs: [ // 第0列(对应creating date和update date) { targets: 0, orderable: true, // 允许两个表头都能触发排序 orderHeader: true, // 用jQuery选择器定位两个表头单元格 headerCell: 'thead tr:first-child th:eq(0), thead tr:last-child th:eq(0)' }, // 第1列对应name表头 { targets: 1, orderable: true, headerCell: 'thead tr:first-child th:eq(1)' }, // 第2列对应location表头 { targets: 2, orderable: true, headerCell: 'thead tr:first-child th:eq(2)' } ], // 可选:设置默认排序规则,这里按第0列升序排 order: [[0, 'asc']] }); }); </script> </body> </html>
关键配置解释
columnDefs:这是解决问题的核心,咱们通过它给每一列明确指定对应的表头单元格,让DataTables知道哪个表头对应哪一列的排序。orderHeader: true:专门用来处理同一列对应多个表头的情况,开启后,绑定的所有表头单元格都能点击触发排序,这样creating date和update date点了都能排第0列。headerCell:用jQuery选择器精准定位表头,确保每一列和表头一一对应。
小提醒
- 你的DataTables版本是1.10.19,完全支持
orderHeader这个参数,放心用就行。 - 那个跨两列的
comment表头不需要配置排序,因为它对应的是name和location两列,排序还是得针对具体的数据列来操作哦。
内容的提问来源于stack exchange,提问作者David Portabella
相关产品推荐
相关产品推荐

