值得一看
广告
彩虹云商城
广告

热门广告位

使用 DataTables 和 JavaScript 数组创建可搜索列的表格

使用 datatables 和 javascript 数组创建可搜索列的表格

本文档详细介绍了如何使用 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 定义列标题。

立即学习“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 结构

以下是完整的 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>
<table id="example" class="display dataTable cell-border">
</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 数组初始化表格,并为每一列添加搜索功能。这种方法可以帮助你快速创建具有交互式过滤功能的表格,提升用户体验。希望本教程对你有所帮助!

温馨提示: 本文最后更新于2025-08-25 22:43:04,某些文章具有时效性,若有错误或已失效,请在下方留言或联系在线客服
文章版权声明 1 本网站名称: 创客网
2 本站永久网址:https://new.ie310.com
1 本文采用非商业性使用-相同方式共享 4.0 国际许可协议[CC BY-NC-SA]进行授权
2 本站所有内容仅供参考,分享出来是为了可以给大家提供新的思路。
3 互联网转载资源会有一些其他联系方式,请大家不要盲目相信,被骗本站概不负责!
4 本网站只做项目揭秘,无法一对一教学指导,每篇文章内都含项目全套的教程讲解,请仔细阅读。
5 本站分享的所有平台仅供展示,本站不对平台真实性负责,站长建议大家自己根据项目关键词自己选择平台。
6 因为文章发布时间和您阅读文章时间存在时间差,所以有些项目红利期可能已经过了,能不能赚钱需要自己判断。
7 本网站仅做资源分享,不做任何收益保障,创业公司上收费几百上千的项目我免费分享出来的,希望大家可以认真学习。
8 本站所有资料均来自互联网公开分享,并不代表本站立场,如不慎侵犯到您的版权利益,请联系79283999@qq.com删除。

本站资料仅供学习交流使用请勿商业运营,严禁从事违法,侵权等任何非法活动,否则后果自负!
THE END
喜欢就支持一下吧
点赞6赞赏 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容