如何将DataTables的排序功能设置在表头第一行(默认在第二行)
如何将DataTables的排序功能设置在表头第一行(默认在第二行)
我懂你现在的烦恼!当DataTables遇到多行表头时,默认会把排序功能绑定到<thead>里的最后一行,这就是为啥你的排序图标偏偏出现在第二行的原因。别担心,咱们只需要一个简单的配置就能搞定,再调整下搜索框的代码就完美了~
解决方案核心:orderCellsTop 配置项
DataTables提供了orderCellsTop这个配置,当设置为true时,它会优先把排序功能绑定到<thead>中的第一行表头,而不是默认的最后一行。接下来针对你的两个例子分别给出修改方案:
1. 客户端渲染表格的修改方案
只需要在DataTables初始化配置里加上orderCellsTop: true即可,其他代码保持不变:
$(document).ready( function () { var table = $('#example').DataTable({ colReorder: true, orderCellsTop: true, // 关键:让排序绑定到第一行表头 "footerCallback": function ( row, data, start, end, display ) { var api = this.api(), data; // Append footer if it doesn't exist if ($('#example').find('tfoot').length ===0) { var footer = $('<tfoot><tr><th colspan="6">g</th></tr></tfoot>'); $('#example').append(footer); } // Remove the formatting to get integer data for summation var intVal = function ( i ) { return typeof i === 'string' ? i.replace(/[\$,]/g, '')*1 : typeof i === 'number' ? i : 0; }; // Total over all pages total = api .column( 5 ) .data() .reduce( function (a, b) { return intVal(a) + intVal(b); }, 0 ); // Total over this page pageTotal = api .column( 5, { page: 'current'} ) .data() .reduce( function (a, b) { return intVal(a) + intVal(b); }, 0 ); // Update footer $( '#example tfoot th:eq(0)' ).html( '$'+pageTotal +' ( $'+ total +' total)' ); } }); } );
2. 服务端渲染表格的修改方案
除了加上orderCellsTop: true,还要调整搜索框的挂载位置,确保它放到第二行表头里,而不是替换第一行的内容:
$(document).ready(function() { var table = $('#example').DataTable({ processing: true, serverSide: true, ajax: { /* 保留你的ajax配置 */ }, pageLength: 10, searching: true, orderCellsTop: true, // 关键:排序绑定到第一行表头 initComplete: function() { this.api() .columns() .every(function() { let column = this; let title = column.header().textContent; // 找到当前列对应的第二行表头单元格 let secondHeaderCell = $(column.header()) .closest('tr') // 找到第一行的tr .next() // 切换到第二行tr .find('th') // 找到第二行的所有th .eq(column.index()); // 匹配当前列的索引 // 创建搜索输入框 let input = document.createElement('input'); input.placeholder = "Search " + title; secondHeaderCell.empty().append(input); // 把输入框放到第二行单元格中 // 输入框搜索事件监听 input.addEventListener('keyup', (e) => { if (column.search() !== input.value) { column.search(input.value).draw(); } }); }); } }); });
这样修改后,排序功能就会乖乖出现在第一行表头,第二行的搜索框也能正常工作啦~
备注:内容来源于stack exchange,提问作者ghost_of_the_code




