jQuery DataTables仅筛选特定列

jQuery DataTables Filtering for Specific Columns Only

本文关键字:筛选 DataTables jQuery      更新时间:2023-09-26

我正在使用jQuery插件DataTables(http://datatables.net)用于分页、搜索功能和过滤。

有一个过滤功能(http://datatables.net/release-datatables/examples/api/multi_filter_select.html)为每列放置表单选择元素。

我的问题是,我不希望过滤器为每一列选择元素,只为一些。我修改了原始代码,因为我只想进行"是/否"筛选,并且我的第一列包含用户名。

如何从第一列中删除表单选择元素?

JavaScript:

<script type="text/javascript">
$(document).ready(function() {
(function($) {
/*
 * Function: fnGetColumnData
 * Purpose:  Return an array of table values from a particular column.
 * Returns:  array string: 1d data array
 * Inputs:   object:oSettings - dataTable settings object. This is always the last argument past to the function
 *           int:iColumn - the id of the column to extract the data from
 *           bool:bUnique - optional - if set to false duplicated values are not filtered out
 *           bool:bFiltered - optional - if set to false all the table data is used (not only the filtered)
 *           bool:bIgnoreEmpty - optional - if set to false empty values are not filtered from the result array
 * Author:   Benedikt Forchhammer <b.forchhammer /AT' mind2.de>
 */
$.fn.dataTableExt.oApi.fnGetColumnData = function ( oSettings, iColumn, bUnique, bFiltered, bIgnoreEmpty ) {
    // check that we have a column id
    if ( typeof iColumn == "undefined" ) return new Array();
    // by default we only want unique data
    if ( typeof bUnique == "undefined" ) bUnique = true;
    // by default we do want to only look at filtered data
    if ( typeof bFiltered == "undefined" ) bFiltered = true;
    // by default we do not wany to include empty values
    if ( typeof bIgnoreEmpty == "undefined" ) bIgnoreEmpty = true;
    // list of rows which we're going to loop through
    var aiRows;
    // use only filtered rows
    if (bFiltered == true) aiRows = oSettings.aiDisplay;
    // use all rows
    else aiRows = oSettings.aiDisplayMaster; // all row numbers
    // set up data array   
    var asResultData = new Array();
    for (var i=0,c=aiRows.length; i<c; i++) {
        iRow = aiRows[i];
        var aData = this.fnGetData(iRow);
        var sValue = aData[iColumn];
        // ignore empty values?
        if (bIgnoreEmpty == true && sValue.length == 0) continue;
        // ignore unique values?
        else if (bUnique == true && jQuery.inArray(sValue, asResultData) > -1) continue;
        // else push the value onto the result data array
        else asResultData.push(sValue);
    }
    return asResultData;
}}(jQuery));

function fnCreateSelect( aData )
{
    return '<select><option value="">Select</option><option value="Yes">Yes</option><option value="No">No</option></select>';
}
   var oTable = $('#results').dataTable({
         "sDom": '<<"filters"f><"clear"><"top"Tp><"clear">rt<"bottom"il>>',
         "iDisplayLength": 5,
         "sPaginationType": "full_numbers",
         "bSortCellsTop": true,
         "oLanguage": {
                    "sSearch": "Search all columns:"
          },
         "aoColumns": [
                null,
                { "sType": "title-string" },
                { "sType": "title-string" },
                { "sType": "title-string" },
                { "sType": "title-string" }
            ],
        "oTableTools": {
            "sSwfPath": "../../scripts/TableTools/copy_cvs_xls_pdf.swf" 
        }         
    });  

 /* Add a select menu for each TH element in the table footer */
    $("thead #filter td").each( function ( i ) {
        this.innerHTML = fnCreateSelect( oTable.fnGetColumnData(i) );
        $('select', this).change( function () {
            oTable.fnFilter( $(this).val(), i );
        } );
    } );    
} );
</script>

HTML:

<table id="results" class="display">
    <thead>
        <tr id="labels">
            <th>1</th>
            <th>2</th>
            <th>3</th>
            <th>4</th>
            <th>5?</th>
        </tr>
        <tr id="filter">
            <td>1</td>
            <td>2</td>
            <td>3</td>
            <td>4</td>
            <td>5?</td>
        </tr>
    </thead>
    <tbody>
    ...
    </tbody>
</table>

您可以修改选择器以忽略第一个<td>元素。每个匹配元素的索引应比相应的列索引小1。

/* Add a select menu for each TH element except the first in the table footer */
$("thead #filter td:not(:eq(0))").each( function ( i ) {
    var columnIndex = i + 1;
    this.innerHTML = fnCreateSelect( oTable.fnGetColumnData(columnIndex) );
    $('select', this).change( function () {
        oTable.fnFilter( $(this).val(), columnIndex );
    } );
});

如果您希望能够指定需要过滤器的列索引,一种方法是执行类似的操作

var filterIndexes = [3, 4];
$('td', '#filter').each( function ( i ) {
    if ($.inArray(i, filterIndexes) != -1) {
        this.innerHTML = fnCreateSelect( oTable.fnGetColumnData(i) );
        $('select', this).change( function () {
            oTable.fnFilter( $(this).val(), i );
        });
    }
});

或者,如果您想通过将类.filter添加到要筛选其列的任何<th>元素来控制筛选器,则可以执行类似的操作

$('th', '#labels').each( function(i) {
    if ($(this).hasClass( 'filter' )) {
        $('td', '#filter').eq(i)
          .html( fnCreateSelect(oTable.fnGetColumnData(i)) )
          .find('select')
          .change(function () { oTable.fnFilter($(this).val(), i); });
    }
});    

没有经过测试,但你得到了这样的想法:(

在当前版本中根据http://www.datatables.net/examples/api/multi_filter_select.html,对于一个专栏,我幸运地获得了this.api().column(0).every:

$(document).ready(function() {
    $('#mytable').DataTable( {
        initComplete: function () {
            this.api().column(0).every( function () {
                var column = this;
                var select = $('<select><option value=""></option></select>')
                    .appendTo( $(column.header()).empty() )
                    .on( 'change', function () {
                        var 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>' )
                } );
            } );
        },
    } );
} );

但是,那时还需要"每一个"吗?如何针对多个列?

我借调了matt voda答案,将此代码用于第一列:

this.api().column( [0] ).every 

并使用此代码了解更多信息:

this.api().column( [0,1,2] ).every 

在要跳过的tfoot列上,可以将其留空

最简单的方法是将其用于不需要的列:

<input type="hidden">

对于基本搜索,您可以从中获得想法

$('tbody tr').addClass('visible');  

$('thead tr th input:text').keyup(function(event) {      

  if (event.keyCode == 27 || $(this).val() == '')
      {  ``$('tbody tr td ').show();
     }
  }
$("tfoot th").each( function ( i ) {
  if(i>=3 && i<=6)
    this.innerHTML = fnCreateSelect( oTable.fnGetColumnData(i) );
  $('select', this).change( function () {
    oTable.fnFilter( $(this).val(), i );
  });
});

这是插入"特定列的筛选器"的最佳方式。

i - Is Number Of Coulmn.

<th></th>-*标记号必须等于Columns。

甚至还有一种非常简单的方法:对于那些不需要筛选的列,只需将<th> in <tfoot>的可见性设置为隐藏即可示例:

<th style="visibility: hidden;">Something</th>

我所做的最简单的方法是在columns数组中给searchablefalse。它就像一种魅力:闪闪发光:

columns: [
    {data: 'name', name: 'name'},
    {data: 'description', name: 'description'},
    {data: 'company.name', name: 'company_id'},
    {data: 'status', name: 'status', "searchable": false},
    {data: 'created_at', name: 'created_at'},
    { data: null, name: '',  "searchable": false },
],