本教程详细指导如何在DataTables中,利用JavaScript数组数据初始化表格,并为每一列添加交互式的搜索过滤功能。内容涵盖数据与列定义的匹配、动态生成表头<thead>、以及通过initComplete回调实现列搜索框的完整逻辑,旨在帮助开发者构建功能强大的可搜索表格。
1. DataTables基础初始化与数据准备
在使用datatables时,如果数据源是javascript的数组(数组的数组形式),我们需要正确地将其与列定义(columns选项)结合。一个常见的错误是数据列数与列标题定义数量不匹配,或者语法错误。
数据与列定义示例:
const dataSet = [ ['a', 'b', 'x'], ['c', 'd', 'y'], ['e', 'f', 'z'] ]; const headers = [{ 'title': 'A' }, { 'title': 'B' }, { 'title': 'C' }]; $(document).ready(function() { $('#example').DataTable({ data: dataSet, columns: headers, }); });
注意事项:
- dataSet中的每个内部数组代表一行数据,其元素数量必须与headers数组中定义的列数一致。
- headers数组中的每个对象定义一个列,title属性用于设置列的标题。
2. 实现DataTables列搜索功能
为了在DataTables的每一列中添加独立的搜索框,我们需要利用DataTables的initComplete回调函数。此函数在表格完全初始化后执行,允许我们对dom进行操作并绑定事件。
核心配置与逻辑:
立即学习“Java免费学习笔记(深入)”;
$(document).ready(function() { // 假设 dataSet 和 headers 已定义 // 1. 如果html中没有<thead>,需要动态创建 // 参考下一节“动态生成表头(<thead>)” // 克隆表头行并添加'filters'类,将其追加到表头 $('#example thead tr') .clone(true) .addClass('filters') .appendTo('#example thead'); var table = $('#example').DataTable({ data: dataSet, // 绑定数据 columns: headers, // 绑定列定义 orderCellsTop: true, // 确保排序图标在顶部 fixedHeader: true, // 可选:固定表头 initComplete: function() { var api = this.api(); // 遍历每一列 api.columns().eq(0).each(function(colIdx) { // 获取当前列的筛选器单元格 var cell = $('.filters th').eq( $(api.column(colIdx).header()).index() ); var title = $(cell).text(); // 获取原始标题 // 在筛选器单元格中插入文本输入框 $(cell).html('<input type="text" placeholder="' + title + '" />'); // 为输入框绑定事件 $('input', $('.filters th').eq($(api.column(colIdx).header()).index())) .off('keyup change') // 解绑可能存在的旧事件 .on('change', function(e) { $(this).attr('title', $(this).val()); var regexr = '({search})'; var cursorPosition = this.selectionStart; // 对当前列进行搜索 api .column(colIdx) .search( this.value != '' ? regexr.replace('{search}', '(((' + this.value + ')))') : '', this.value != '', this.value == '' ) .draw(); // 重绘表格以显示搜索结果 }) .on('keyup', function(e) { e.stopPropagation(); // 阻止事件冒泡 $(this).trigger('change'); // 触发change事件进行搜索 // 可选:保持光标位置 // $(this).focus()[0].setSelectionRange(cursorPosition, cursorPosition); }); }); }, }); });
关键点解析:
- orderCellsTop: true:当有多个表头行时,确保排序功能应用于最顶部的表头。
- fixedHeader: true:这是DataTables的一个扩展,用于固定表头,与列搜索功能结合使用时体验更佳。
- initComplete:在此回调中,我们可以安全地操作已渲染的表格DOM。
- api.columns().eq(0).each(function(colIdx) { … }):遍历表格中的每一列。
- $(‘.filters th’).eq(…):选择新克隆的.filters行中的对应列单元格。
- $(cell).html(‘<input type=”text” placeholder=”‘ + title + ‘” />’):将搜索输入框添加到每个列的筛选器单元格中。
- off(‘keyup change’).on(‘change’, …).on(‘keyup’, …):
- api.column(colIdx).search(…):这是DataTables API中用于对特定列进行搜索的方法。参数包括搜索值、是否使用正则表达式、是否智能搜索等。
- draw():在搜索条件改变后,必须调用此方法来重新绘制表格,以应用新的过滤条件。
3. 动态生成表头(<thead>)
如果你的HTML表格结构最初没有<thead>标签,或者<thead>中没有包含足够的<th>元素来匹配你的列定义,那么上述的列搜索代码将无法正常工作,因为$(‘#example thead tr’).clone(true)找不到目标。在这种情况下,我们需要在DataTables初始化之前,动态地创建并添加<thead>。
HTML表格示例(无<thead>):
<table id="example" class="display dataTable cell-border" style="width:100%"> </table>
动态生成<thead>的JavaScript代码:
// 假设 headers 已定义 var th = '<thead><tr>'; headers.forEach(header => th = th + '<th>' + header.title + '</th>'); th = th + '</tr></thead>'; $(th).appendTo('#example');
这段代码会根据headers数组中的定义,生成一个包含所有列标题的<thead>结构,并将其追加到#example表格中。这样,后续的DataTables初始化和列搜索逻辑就能找到正确的表头元素进行操作。
4. 完整示例与注意事项
将上述所有组件整合,我们可以构建一个完整的、功能齐全的DataTables列搜索示例。
HTML结构 (index.html):
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>DataTables列搜索教程</title> <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css"> <!-- DataTables FixedHeader 扩展的CSS,如果使用fixedHeader:true则需要 --> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/fixedheader/3.1.7/css/fixedHeader.dataTables.min.css"> <script src="https://cdn.datatables.net/fixedheader/3.1.7/js/dataTables.fixedHeader.min.js"></script> <style> /* 可选:为筛选器行添加一些样式 */ .filters input { width: 100%; box-sizing: border-box; padding: 3px; border: 1px solid #ccc; border-radius: 3px; } </style> </head> <body> <div style="margin: 20px;"> <h2>DataTables高级列搜索示例</h2> <table id="example" class="display dataTable cell-border" style="width:100%"> <!-- <thead> 将由JavaScript动态生成 --> </table> </div> <script> $(document).ready(function() { const dataSet = [ ['Apple', 'red', 'Fruit'], ['Banana', 'Yellow', 'Fruit'], ['Carrot', 'Orange', 'Vegetable'], ['Grape', 'Purple', 'Fruit'], ['Spinach', 'Green', 'Vegetable'] ]; const headers = [{ 'title': '名称' }, { 'title': '颜色' }, { 'title': '分类' }]; // 动态生成表头 <thead> var th = '<thead><tr>'; headers.forEach(header => th = th + '<th>' + header.title + '</th>'); th = th + '</tr></thead>'; $(th).appendTo('#example'); // 克隆表头行并添加'filters'类,将其追加到表头 $('#example thead tr') .clone(true) .addClass('filters') .appendTo('#example thead'); var table = $('#example').DataTable({ data: dataSet, columns: headers, orderCellsTop: true, // 确保排序图标在顶部 fixedHeader: true, // 启用固定表头 initComplete: function() { var api = this.api(); // 遍历每一列 api.columns().eq(0).each(function(colIdx) { // 获取当前列的筛选器单元格 var cell = $('.filters th').eq( $(api.column(colIdx).header()).index() ); var title = $(cell).text(); // 获取原始标题 // 在筛选器单元格中插入文本输入框 $(cell).html('<input type="text" placeholder="搜索 ' + title + '" />'); // 为输入框绑定事件 $('input', $('.filters th').eq($(api.column(colIdx).header()).index())) .off('keyup change') // 解绑可能存在的旧事件 .on('change', function(e) { $(this).attr('title', $(this).val()); var regexr = '({search})'; // 示例中使用占位符,实际DataTables会处理 // 对当前列进行搜索 api .column(colIdx) .search( this.value != '' ? regexr.replace('{search}', '(((' + this.value + ')))') : // 这里的regexr替换逻辑是DataTables内部处理的一部分,通常直接传值即可 '', this.value != '', // 是否使用正则表达式 this.value == '' // 是否智能搜索 ) .draw(); // 重绘表格以显示搜索结果 }) .on('keyup', function(e) { e.stopPropagation(); // 阻止事件冒泡 $(this).trigger('change'); // 触发change事件进行实时搜索 }); }); }, }); }); </script> </body> </html>
总结: 通过本教程,我们学习了如何利用JavaScript数组数据初始化DataTables,并为表格的每一列实现高级的搜索过滤功能。关键步骤包括确保数据与列定义的匹配、动态生成<thead>以支持表头操作,以及在initComplete回调中通过DataTables API操作DOM并绑定搜索事件。遵循这些步骤,开发者可以创建出用户体验更佳、功能更强大的数据表格。