首页 > 解决方案 > 如何使用数据表仅对一列应用搜索过滤器

问题描述

我有一张表,我想在特定列上应用搜索过滤器。我看到了许多有关如何执行此操作的链接,但是在我的代码中,当我插入一个 javascript 块来执行过滤器时,没有任何显示。

 <html>
 <head>
  <link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">


  </head>
 <body>
 <table id="example">
   <thead>
   <tr><th>Sites</th></tr>
  </thead>
  <tbody>
     <tr><td>SitePoint</td></tr>
     <tr><td>Learnable</td></tr>
     <tr><td>Flippa</td></tr>
   </tbody>
  </table>
  <script>
  $(function(){
 $("#example").dataTable();
 })
  </script>

我的困惑是这段代码在哪里(适合主代码)?

  <script>
  $(document).ready(function() {
  // Setup - add a text input to each footer cell
  $('#example tfoot th').each( function () {
    var title = $(this).text();
    $(this).html( '<input type="text" placeholder="Search '+title+'" 
     />' );
      } );

   // DataTable
   var table = $('#example').DataTable();

    // Apply the search
   table.columns().every( function () {
    var that = this;

    $( 'input', this.footer() ).on( 'keyup change', function () {
        if ( that.search() !== this.value ) {
            that
                .search( this.value )
                .draw();
        }
    } );
} );
} );
</script>

标签: javascripthtmlfilter

解决方案


从他们的来源:

$('#example thead tr').clone(true).appendTo( '#example thead' );
    $('#example thead tr:eq(1) th').each( function (i) {
        var title = $(this).text();
        $(this).html( '<input type="text" placeholder="Search '+title+'" />' );

        $( 'input', this ).on( 'keyup change', function () {
            if ( table.column(i).search() !== this.value ) {
                table
                    .column(i)
                    .search( this.value )
                    .draw();
            }
        } );
    } );

    var table = $('#example').DataTable( {
        orderCellsTop: true,
        fixedHeader: true
    } );

这段代码在 DOM 被渲染后执行。

克隆 id 用于修复表列名称从页面滚动。你也需要这个脚本


推荐阅读