使用 DataTable.js 的 js 源数据的单独列搜索过滤器,过滤器位于顶部

2024-03-07

我无法将过滤器选择放在顶部。我如何实现?

我坚持使用 initComplete 选项,因为它仅在 DataTable 完全初始化后触发一次,并且可以安全地调用 API 方法。

另外,我到底应该在哪里使列下拉值变得唯一

const dataSet = [
      ["Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800"],
      ["Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750"],
      ["Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000"],
    ];

    const dataTable = $('#example').DataTable({
        data: dataSet,
        dom: 't',
        columns: ['Name', 'Job Title', 'Location', 'Id', 'Hire Date', 'Salary'].map(header => ({
            title: header
          })),
        initComplete: function () {
          //purge existing <tfoot> if exists
          $('#example tfoot').remove();
          //append new footer to the table
          $('#example').append('<tfoot><tr></tr></tfoot>');
          //iterate through table columns
          this.api().columns().every(function () {
            //append <select> node to each column footer inserting 
            //current column().index() as a "colindex" attribute
            $('#example tfoot tr').append(`<th><select colindex="${this.index()}"></select></th>`);
            //grab unique sorted column entries and translate those into <option> nodes
            const options = this.data().unique().sort().toArray().reduce((options, item) => options += `<option value="${item}">${item}</option>`, '<option value=""></option>');
            //append options to corresponding <select>
            $(`#example tfoot th:eq(${this.index()}) select`).append(options);
          });
        }
      });

    $('#example').on('change', 'tfoot select', function (event) {
      //use "colindex" attribute value to search corresponding column for selected option value
      dataTable.column($(event.target).attr('colindex')).search($(event.target).val()).draw();
    })
<link href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>

<table id="example">
</table>

您可以使用以下方法替换列标题的内容.appendTo( $(column.header()).empty() )。您还可以在以下内容中添加事件监听器initComplete-回调并将它们直接附加到输入。

const dataSet = [
  ["Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800"],
  ["Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750"],
  ["Lorem ipsum", "Accountant", "Edinburgh", "1562", "2011/07/25", "$86,000"],
  ["Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000"],
];

const dataTable = $('#example').DataTable({
  data: dataSet,
  dom: 't',
  columns: ['Name', 'Job Title', 'Location', 'Id', 'Hire Date', 'Salary'].map(header => ({
    title: header
  })),
  initComplete: function () {
    this.api().columns().every( function () {
      let column = this; 
      let select = $('<select><option value="">All</option></select>')
      .appendTo( $(column.header()).empty() )
      .on( 'change, click', function ( e ) {
        e.stopPropagation();
        let val = $.fn.dataTable.util.escapeRegex( $(this).val() );
        column.search( val ? '^'+val+'$' : '', true, false ).draw();
      });
      column.data().unique().sort().each( function ( d, j ) {
        select.append( '<option value="'+d+'">'+d+'</option>' )
      });
    });
  }
});
<link href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>

<table id="example">
</table>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 DataTable.js 的 js 源数据的单独列搜索过滤器,过滤器位于顶部 的相关文章