如何在数据表中创建列搜索,如果表是使用javascript的数组的数组的数据初始化?

svmlkihl  于 2023-05-21  发布在  Java
关注(0)|答案(1)|浏览(177)

我是写代码的新手,我在使用数据表初始化表时遇到了麻烦。我试图实现的是创建一个表,用户可以搜索/过滤表的每一列。
我知道如何简单地初始化数据表,如:

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和header放在哪里:

$(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({
        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');
                            $(this)
                                .focus()[0]
                                .setSelectionRange(cursorPosition, cursorPosition);
                        });
                });
        },
    });
});

创建一个表,用户可以使用datatables(link)搜索/过滤表中的每一列

qacovj5a

qacovj5a1#

首先,你的问题中的基本示例不起作用:

const dataSet = [['a','b'],['c','d'],['e','f']];
const headers = [{'title':'A'},{'title': 'B'},{'title': 'C'}}

$(document).ready(function () {
    $('#example').DataTable({
        data: dataSet,
        columns: headers,
    });
});

你需要先解决这个问题:
1.在const headers中,数据需要以}]而不是}}结束。我想这只是一个错字。

  1. headers数组定义了三个列标题。但是dataSet中的每一行数据只定义了两列数据。因此,您必须使这两个数据集兼容-例如,通过添加第三列数据或删除第三列标题。下面是第三列数据:
const dataSet = [['a','b','x'],['c','d','y'],['e','f','z']];

现在你可以将上面的代码添加到更复杂的示例中,并将同样的两个选项添加到DataTable中:

data: dataSet,
columns: headers,

如果你的HTML表没有定义任何标题,那么你需要执行一个额外的步骤。
我假设你有这样的东西:

<table id="example" class="display dataTable cell-border" style="width:100%">
</table>

请注意,<table>标记没有任何<thead>内容。
因此,您必须创建<thead> HTML并将其添加到上表中。这是因为代码的其余部分(构建列过滤器)假设此标题行已经存在。你可以在official example中看到这一点。
以下是构建缺失的<thead>行并将其添加到<table>的一种方法:

// 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' );

现在已经将标题行添加到了表中,代码的其余部分可以正常工作,无需任何额外的更改。
完整代码如下所示:

$(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);
            });
        });
    },
  });
});
<!doctype html>
<html>

<head>
  <meta charset="UTF-8">
  <title>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>


</body>

</html>

相关问题