本教程详细指导如何在Datatables中使用JavaScript数组数据源,实现强大的每列搜索过滤功能。我们将从数据与表头配置的兼容性入手,逐步讲解如何动态生成表头(如果缺失),并集成DataTables的initComplete回调函数,为每一列添加可交互的搜索输入框,从而提升数据表格的用户体验和查询效率。
1. DataTables基础初始化与数据兼容性
在使用datatables时,如果数据源是javascript的数组,并且希望为每列添加搜索功能,首先需要确保datatables的基础初始化正确无误。一个常见的错误是数据列数与表头定义不匹配。
示例:正确的数据与表头配置
假设我们有以下数据和表头定义:
const dataSet = [ ['a', 'b', 'x'], ['c', 'd', 'y'], ['e', 'f', 'z'] ]; const headers = [ { 'title': 'A' }, { 'title': 'B' }, { 'title': 'C' } ];
这里,dataSet中的每个子数组代表一行数据,包含三个元素。headers数组定义了三个列标题。两者数量一致,这是DataTables正常工作的基本前提。
基础的DataTables初始化代码如下:
立即学习“Java免费学习笔记(深入)”;
此代码将dataSet作为表格数据,headers作为列定义,初始化一个基本的DataTables实例。
2. 动态生成表头(thead)
在实现列搜索功能时,DataTables的许多高级特性(尤其是涉及表头操作的,如列过滤)都依赖于html表格中存在一个<thead>元素。如果你的HTML表格仅包含一个空的<table>标签,例如:
<table id="example" class="display dataTable cell-border" style="width:100%"> </table>
那么你需要在使用DataTables初始化之前,动态地创建并插入<thead>元素。这是因为后续用于生成列过滤器的代码会克隆现有的表头行。
动态生成<thead>的JavaScript代码:
// 根据headers数组动态生成<thead>元素 var th = '<thead><tr>'; headers.forEach(header => th = th + '<th>' + header.title + '</th>'); th = th + '</tr></thead>'; $(th).appendTo('#example');
这段代码会遍历headers数组,为每个表头对象创建一个<th>标签,然后将所有<th>包裹在<tr>和<thead>中,最后将其添加到id为example的表格中。
3. 实现每列搜索功能
DataTables提供了initComplete回调函数,允许我们在表格完全初始化后执行自定义操作。我们将利用此回调函数来为每列添加搜索输入框。
核心逻辑步骤:
- 克隆表头行并添加过滤器类: $(‘#example thead tr’).clone(true).addClass(‘filters’).appendTo(‘#example thead’); 这行代码克隆了现有的表头行,并将其添加回<thead>中,同时为其添加filters类,以便后续定位。
- 遍历每一列: 在initComplete回调中,通过api.columns().eq(0).each(function (colIdx) { … }); 遍历表格的每一列。
- 创建搜索输入框: 对于每一列,获取其表头单元格,并用一个带有占位符的<input type=”text”>替换其内容。占位符通常是该列的标题。
- 绑定搜索事件: 为新创建的输入框绑定change和keyup事件。
- change事件用于执行实际的列搜索。它获取输入框的值,并使用api.column(colIdx).search(…)方法对当前列进行过滤。
- keyup事件用于在用户输入时即时触发change事件,实现实时搜索效果,并通过e.stopPropagation()阻止事件冒泡,避免干扰DataTables的其他事件。
完整JavaScript代码示例:
$(document).ready(function() { const dataSet = [ ['a', 'b', 'x'], ['c', 'd', 'y'], ['e', 'f', 'z'] ]; const headers = [ { 'title': 'A' }, { 'title': 'B' }, { 'title': 'C' } ]; // 1. 动态生成<thead>,如果HTML中没有定义 var th = '<thead><tr>'; headers.forEach(header => th = th + '<th>' + header.title + '</th>'); th = th + '</tr></thead>'; $(th).appendTo('#example'); // 2. 克隆表头行并添加过滤器行 $('#example thead tr') .clone(true) .addClass('filters') .appendTo('#example thead'); var table = $('#example').DataTable({ // 3. 配置DataTables数据源和列定义 data: dataSet, columns: headers, // 4. 其他DataTables选项 orderCellsTop: true, // 确保排序图标在顶部表头 fixedHeader: true, // 固定表头,如果需要 // 5. initComplete回调,实现列搜索逻辑 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(); // 获取原始列标题作为placeholder // 在单元格中插入搜索输入框 $(cell).html('<input type="text" placeholder="' + title + '" />'); // 为输入框绑定change和keyup事件 $('input', $('.filters th').eq($(api.column(colIdx).header()).index())) .off('keyup change') // 先解绑,防止重复绑定 .on('change', function(e) { $(this).attr('title', $(this).val()); // 将当前值设置为title属性 var regexr = '({search})'; // 用于构建正则表达式 // 执行列搜索 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事件进行搜索 }); }); }, }); });
4. HTML结构与必要的库引入
为了使上述JavaScript代码正常工作,你的HTML页面需要包含一个<table>元素,并引入jquery和DataTables的JS/css库。
HTML结构:
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>DataTables列搜索教程</title> <!-- 引入jQuery库 --> <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <!-- 引入DataTables JS和CSS --> <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> </body> </html>
5. 注意事项与总结
- 数据与表头匹配: 始终确保dataSet中的每行数据元素数量与headers数组中定义的列数一致。
- <thead>的重要性: 如果HTML中没有显式定义<thead>,请务必在DataTables初始化前通过JavaScript动态生成。这是列过滤器能够正确附加的前提。
- 事件处理: off(‘keyup change’).on(‘change’, …).on(‘keyup’, …)的模式确保了事件的正确绑定和实时搜索效果。e.stopPropagation()在keyup中是关键,防止不必要的事件冒泡。
- 搜索逻辑: api.column(colIdx).search(…)是DataTables提供的核心列搜索方法。示例中的regexr.replace(‘{search}’, ‘(((‘ + this.value + ‘)))’)用于构建一个正则表达式进行匹配,可以根据需求调整其匹配模式。
- orderCellsTop和fixedHeader: 这两个选项不是实现列搜索的必需品,但它们在用户体验上有所帮助。orderCellsTop: true确保排序图标在顶部表头,fixedHeader: true则使表头在滚动时保持固定。
通过以上步骤,你就可以成功地在DataTables中使用JavaScript数组作为数据源,并为每列实现强大的搜索过滤功能,极大地提升表格的交互性和可用性。