
本文档详细介绍了如何使用 DataTables 插件,结合 JavaScript 数组数据,创建具有列搜索功能的交互式表格。我们将从基础的 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。假设我们有一个 JavaScript 数组 dataSet 包含表格数据,以及一个数组 headers 定义列标题。
立即学习“Java免费学习笔记(深入)”;
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 结构:
<!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>通过本教程,你学习了如何使用 DataTables 和 JavaScript 数组初始化表格,并为每一列添加搜索功能。这种方法可以帮助你快速创建具有交互式过滤功能的表格,提升用户体验。希望本教程对你有所帮助!
以上就是使用 DataTables 和 JavaScript 数组创建可搜索列的表格的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号