jQuery 数据表:将列可见性与单个列过滤器(文本输入)相结合?

jQuery Datatables: Combining column visibility with individual column filters (text inputs)?

我正在使用 basic column visibility and individual column searching (text inputs)

问题在于,当用户将先前隐藏的列添加到 table 时,该列的文本字段框不会出现。因此,用户无法过滤该列。

还有人知道如何为隐藏列启用过滤器吗?理想情况下,这不会导致清除其他过滤器中的文本的副产品(如果用户确实在其他过滤器中输入了文本)。

这是我的过滤代码:

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

        if ((title != '') && !(title.includes("$"))) {
            // Then the current column is *not* the Action column.          
            $(this).html( '<span style="color: #515151; font-size:15px;"><i>Filter</i></span> <br> <input type="text"  style="margin-top:10px;" placeholder="'+title+'" /> ' );
        }
    } );

    var table = $('#tableID').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>  

我正在使用这一行来隐藏我想在默认情况下从视图中隐藏的列:

(table.column('.hideCol')).visible(false);

DataTables 中有一个自定义 column-visibility 事件。因此,您可以根据列的当前状态修改 <input> 元素可见性。

例如你有 <input> 渲染函数,像这样:

//function to render input elements
const renderTfootInputs =  () => {
        //grab previous inputs into array
        const prevInputs = [];
        dataTable.columns().every(function(){
            prevInputs.splice(this.index(), 1, $(`#example tfoot [colindex="${this.index()}"]`).val());
        });
        //purge <tfoot> row contents
        $('#example tfoot tr').empty()
        //iterate through table columns
        dataTable.columns().every(function(){
            //if the column is visible
            this.visible() ?
            //append corresponding footer <input>
            $('#example tfoot tr').append(`<th><input colindex="${this.index()}" placeholder="${$(this.header()).text()}" value="${prevInputs[this.index()] || ''}"></input></th>`) :
            true;
        });
};

然后,您可以在列可见性更改时调用它:

$('#example').on('column-visibility.dt', renderTfootInputs);

此方法的完整演示可能如下所示:

//sample data source
const dataSrc = [
 {id: 1, title: 'apple', cat: 'fruit'},
 {id: 2, title: 'pear', cat: 'fruit'},
 {id: 3, title: 'banana', cat: 'fruit'},
 {id: 4, title: 'carrot', cat: 'vegie'},
 {id: 5, title: 'eggplant', cat: 'vegie'}
];
//datatables initialization
const dataTable = $('#example').DataTable({
 data: dataSrc,
 dom: 'Bfrtip',
 buttons: ['colvis'],
 columns: ['id','title','cat'].map(header => ({title: header, data: header})),
 columnDefs: [
  {targets: 0, visible: false}
 ]
});
//append blank footer to the table
$('#example').append('<tfoot><tr></tr></tfoot>');
//function to render input elements
const renderTfootInputs =  () => {
 //grab previous inputs into array
 const prevInputs = [];
 dataTable.columns().every(function(){
  prevInputs.splice(this.index(), 1, $(`#example tfoot [colindex="${this.index()}"]`).val());
 });
 //purge <tfoot> row contents
 $('#example tfoot tr').empty()
 //iterate through table columns
 dataTable.columns().every(function(){
  //if the column is visible
  this.visible() ?
  //append corresponding footer <input>
  $('#example tfoot tr').append(`<th><input colindex="${this.index()}" placeholder="${$(this.header()).text()}" value="${prevInputs[this.index()] || ''}"></input></th>`) :
  true;
 });
};
//initial call of above function
renderTfootInputs();
//call that function each time upon column visibility changes
$('#example').on('column-visibility.dt', renderTfootInputs);
//individual search
$('#example').on('keyup', 'tfoot input', function(event){
 dataTable.column($(event.target).attr('colindex')).search($(event.target).val()).draw();
});
tfoot input {
  display: block;
}

tfoot th {
  padding-left: 10px !important;
}
<!doctype html>
<html>
<head>
  <script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
  <script type="application/javascript" src="https://cdn.datatables.net/buttons/1.5.6/js/dataTables.buttons.min.js"></script>
  <script type="application/javascript" src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.colVis.min.js"></script>
  <script type="application/javascript" src="test.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.5.6/css/buttons.dataTables.min.css">
</head>
 <body>
  <table id="example"></table>
 </body>
</html>

我已经使用这个小片段 hide/Unhide 单独的列搜索,与数据表的列可见性事件集成。

$('#table').on( 'column-visibility.dt', function ( e, settings, column, state ) {
            columnv = settings.aoColumns[column].bVisible;
            if(columnv === false){
                 $('#table').find("tr.filters th:eq('"+column+"')").hide();
            }else{
                 $('#table').find("tr.filters th:eq('"+column+"')").show();
            }
        });