
在使用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,
});
});注意事项:
为了在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);
});
});
},
});
});关键点解析:
如果你的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初始化和列搜索逻辑就能找到正确的表头元素进行操作。
将上述所有组件整合,我们可以构建一个完整的、功能齐全的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并绑定搜索事件。遵循这些步骤,开发者可以创建出用户体验更佳、功能更强大的数据表格。
以上就是DataTables教程:使用JavaScript数组数据实现高级列搜索功能的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号