本文档详细介绍了如何使用 DataTables 插件,结合 JavaScript 数组数据,创建具有列搜索功能的交互式表格。我们将从基础的 DataTables 初始化开始,逐步讲解如何配置列过滤器,并提供完整的代码示例,帮助开发者快速实现可搜索列的 DataTables 表格。
DataTables 列搜索实现教程
DataTables 是一款强大的 jquery 插件,用于增强 html 表格的功能,例如排序、分页和过滤。本教程将指导你如何使用 DataTables 和 JavaScript 数组初始化表格,并为每一列添加搜索功能。
准备工作
首先,确保你已经包含了 DataTables 的必要文件。你需要引入 jQuery 和 DataTables 的 css 和 JavaScript 文件。你可以从 DataTables 官网下载这些文件,或者使用 CDN 链接。
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css"> <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>
初始化 DataTables
接下来,我们需要初始化 DataTables。假设我们有一个 JavaScript 数组 dataSet 包含表格数据,以及一个数组 headers 定义列标题。
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 中的列标题传递给 DataTables,从而创建一个基本的表格。
添加列搜索功能
为了添加列搜索功能,我们需要在表格的每一列的头部添加输入框。当用户在输入框中输入内容时,DataTables 将根据输入的内容过滤该列的数据。
首先,我们需要克隆表头,并在克隆的表头中添加输入框。
$(document).ready(function() { // Setup - add a text input to each footer cell $('#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(); // For each column api .columns() .eq(0) .each(function(colIdx) { // Set the header cell to contain the input element var cell = $('.filters th').eq( $(api.column(colIdx).header()).index() ); var title = $(cell).text(); $(cell).html('<input type="text" placeholder="' + title + '" />'); // On every keypress in this input $( 'input', $('.filters th').eq($(api.column(colIdx).header()).index()) ) .off('keyup change') .on('change', function(e) { // Get the search value $(this).attr('title', $(this).val()); var regexr = '({search})'; //$(this).parents('th').find('select').val(); var cursorPosition = this.selectionStart; // Search the column for that value 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'); }); }); }, }); });
这段代码首先克隆了表头,并添加了 filters 类。然后,在 initComplete 回调函数中,我们遍历每一列,并在该列的头部单元格中添加一个输入框。当用户在输入框中输入内容时,我们使用 api.column(colIdx).search() 方法来过滤该列的数据。
完整的 HTML 结构
以下是完整的 HTML 结构:
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>DataTables Column Search Demo</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"> <link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css"> </head> <body> <div style="margin: 20px;"> <table id="example" class="display dataTable cell-border" style="width:100%"> </table> </div> <script> $(document).ready(function() { const dataSet = [ ['a', 'b', 'x'], ['c', 'd', 'y'], ['e', 'f', 'z'] ]; const headers = [{ 'title': 'A' }, { 'title': 'B' }, { 'title': 'C' }]; // add a header row to your table var th = '<thead><tr>'; headers.forEach(header => th = th + '<th>' + header.title + '</th>'); th = th + '</tr></thead>'; $(th).appendTo('#example'); // Setup - add a text input to each footer cell $('#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(); //console.log( api.columns().eq(0) ); // For each column api .columns() .eq(0) .each(function(colIdx) { //console.log( $(api.column(colIdx).header()).index() ); // Set the header cell to contain the input element var cell = $('.filters th').eq( $(api.column(colIdx).header()).index() ); //console.log( headers[colIdx].title ); var title = $(cell).text(); $(cell).html('<input type="text" placeholder="' + title + '" />'); // On every keypress in this input $( 'input', $('.filters th').eq($(api.column(colIdx).header()).index()) ) .off('keyup change') .on('change', function(e) { // Get the search value $(this).attr('title', $(this).val()); var regexr = '({search})'; //$(this).parents('th').find('select').val(); var cursorPosition = this.selectionStart; // Search the column for that value 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'); //$(this) // .focus()[0] // .setSelectionRange(cursorPosition, cursorPosition); }); }); }, }); }); </script> </body> </html>
注意事项
- 确保 dataSet 和 headers 的数据结构匹配,即 dataSet 中的每一行数据的列数应该与 headers 中定义的列数相同。
- 如果你的 HTML 表格没有定义 <thead>,你需要手动创建并添加到表格中。
- initComplete 回调函数是在 DataTables 初始化完成后执行的,你可以在这里添加自定义的逻辑。
- 可以根据需要自定义搜索的逻辑,例如使用正则表达式进行搜索。
总结
通过本教程,你学习了如何使用 DataTables 和 JavaScript 数组初始化表格,并为每一列添加搜索功能。这种方法可以帮助你快速创建具有交互式过滤功能的表格,提升用户体验。希望本教程对你有所帮助!