首页 > web前端 > js教程 > 正文

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

心靈之曲
发布: 2025-08-25 21:24:02
原创
834人浏览过

使用 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,从而创建一个基本的表格。

纳米搜索
纳米搜索

纳米搜索:360推出的新一代AI搜索引擎

纳米搜索 30
查看详情 纳米搜索

添加列搜索功能

为了添加列搜索功能,我们需要在表格的每一列的头部添加输入框。当用户在输入框中输入内容时,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 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>
登录后复制

注意事项

  • 确保 dataSet 和 headers 的数据结构匹配,即 dataSet 中的每一行数据的列数应该与 headers 中定义的列数相同。
  • 如果你的 HTML 表格没有定义 <thead>,你需要手动创建并添加到表格中。
  • initComplete 回调函数是在 DataTables 初始化完成后执行的,你可以在这里添加自定义的逻辑。
  • 可以根据需要自定义搜索的逻辑,例如使用正则表达式进行搜索。

总结

通过本教程,你学习了如何使用 DataTables 和 JavaScript 数组初始化表格,并为每一列添加搜索功能。这种方法可以帮助你快速创建具有交互式过滤功能的表格,提升用户体验。希望本教程对你有所帮助!

以上就是使用 DataTables 和 JavaScript 数组创建可搜索列的表格的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号