
本教程详细指导如何在DataTables中,利用JavaScript数组数据初始化表格,并为每一列添加交互式的搜索过滤功能。内容涵盖数据与列定义的匹配、动态生成表头、以及通过initComplete回调实现列搜索框的完整逻辑,旨在帮助开发者构建功能强大的可搜索表格。 在使用datatables时,如果数据源是javascript的数组(数组的数组形式),我们需要正确地将其与列定义(columns选项)结合。一个常见的错误是数据列数与列标题定义数量不匹配,或者语法错误。 数据与列定义示例: 注意事项: 为了在DataTables的每一列中添加独立的搜索框,我们需要利用DataTables的initComplete回调函数。此函数在表格完全初始化后执行,允许我们对DOM进行操作并绑定事件。 核心配置与逻辑: 动态生成的JavaScript代码: 这段代码会根据headers数组中的定义,生成一个包含所有列标题的结构,并将其追加到#example表格中。这样,后续的DataTables初始化和列搜索逻辑就能找到正确的表头元素进行操作。 将上述所有组件整合,我们可以构建一个完整的、功能齐全的DataTables列搜索示例。 HTML结构 (index.html): 总结:
通过本教程,我们学习了如何利用JavaScript数组数据初始化DataTables,并为表格的每一列实现高级的搜索过滤功能。关键步骤包括确保数据与列定义的匹配、动态生成以支持表头操作,以及在initComplete回调中通过DataTables API操作DOM并绑定搜索事件。遵循这些步骤,开发者可以创建出用户体验更佳、功能更强大的数据表格。1. DataTables基础初始化与数据准备
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,
});
});
2. 实现DataTables列搜索功能
$(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);
});
});
},
});
});<p><strong>关键点解析:</strong></p>
<ul>
<li>orderCellsTop: true:当有多个表头行时,确保排序功能应用于最顶部的表头。</li>
<li>fixedHeader: true:这是DataTables的一个扩展,用于固定表头,与列搜索功能结合使用时体验更佳。</li>
<li>initComplete:在此回调中,我们可以安全地操作已渲染的表格DOM。</li>
<li>api.columns().eq(0).each(function(colIdx) { ... }):遍历表格中的每一列。</li>
<li>$('.filters th').eq(...):选择新克隆的.filters行中的对应列单元格。</li>
<li>$(cell).html('<input type="text" placeholder="' + title + '">'):将搜索输入框添加到每个列的筛选器单元格中。</li>
<li>off('keyup change').on('change', ...).on('keyup', ...):<ul>
<li>off('keyup change'):在重新绑定事件之前,清除可能存在的旧事件监听器,避免重复触发。</li>
<li>on('change', function(e) { ... }):当输入框内容改变时(例如失去焦点或按回车),执行搜索。</li>
<li>on('keyup', function(e) { ... }):在每次按键抬起时触发change事件,实现实时搜索。e.stopPropagation()用于防止按键<a style="color:#f60; text-decoration:underline;" title="事件冒泡" href="https://m.php.cn/zt/16487.html" target="_blank">事件冒泡</a>到DataTables的其他事件<a style="color:#f60; text-decoration:underline;" title="处理器" href="https://m.php.cn/zt/16030.html" target="_blank">处理器</a>。</li>
</ul>
</li>
<li>api.column(colIdx).search(...):这是DataTables API中用于对特定列进行搜索的方法。参数包括搜索值、是否使用<a style="color:#f60; text-decoration:underline;" title="正则表达式" href="https://m.php.cn/zt/15947.html" target="_blank">正则表达式</a>、是否智能搜索等。</li>
<li>draw():在搜索条件改变后,必须调用此方法来重新绘制表格,以应用新的过滤条件。</li>
</ul>
<h3>3. 动态生成表头(<thead>)<p>如果你的HTML表格结构最初没有<thead>标签,或者<thead>中没有包含足够的<th>元素来匹配你的列定义,那么上述的列搜索代码将无法正常工作,因为$('#example thead tr').clone(true)找不到目标。在这种情况下,我们需要在DataTables初始化之前,动态地创建并添加<thead>。<p><strong>HTML表格示例(无<thead>):<pre class="brush:php;toolbar:false;">
// 假设 headers 已定义
var th = '<thead><tr>';
headers.forEach(header => th = th + '<th>' + header.title + '</th>');
th = th + '</tr></thead>';
$(th).appendTo('#example');
4. 完整示例与注意事项
<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><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 + '</script>
';
$(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', $('.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事件进行实时搜索
});
});
},
});
});
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











