在jquery dataTable中隐藏空列的最佳方法

时间:2013-08-01 17:17:13

标签: jquery datatables

我失去了两天寻找一个很好的解决方案,如何通过javascript隐藏jQuery dataTables中的空列,所以我来自我自己的解决方案编写一个新的插件,我认为这将帮助其他人很快做到,如果你发现这个插件很有用,可以随意扩展它并发布你的代码以帮助其他人改进他们的dataTables。

$.fn.dataTableExt.oApi.fnHideEmptyColumns = function ( oSettings, tableObject )
{ 
    /**
     * This plugin hides the columns that are empty.
     * If you are using datatable inside jquery tabs
     * you have to add manually this piece of code
     * in the tabs initialization
     * $("#mytable").datatables().fnAdjustColumnSizing();
     * where #mytable is the selector of table 
     * object pointing to this plugin.
     * This plugin should only be invoked from 
     * fnInitComplete callback.
     * @author John Diaz
     * @version 1.0
     * @date 06/28/2013
     */
    var selector = tableObject.selector; 
    var columnsToHide = [];

    $(selector).find('th').each(function(i) {

        var columnIndex = $(this).index(); 
        var rows = $(this).parents('table').find('tr td:nth-child(' + (i + 1) + ')'); //Find all rows of each column  
        var rowsLength = $(rows).length;
        var emptyRows = 0; 

        rows.each(function(r) { 
            if (this.innerHTML == '') 
                emptyRows++; 
        });  

        if(emptyRows == rowsLength) { 
            columnsToHide.push(columnIndex);  //If all rows in the colmun are empty, add index to array
        }  
    }); 
    for(var i=0; i< columnsToHide.length; i++) {
        tableObject.fnSetColumnVis( columnsToHide[i], false ); //Hide columns by index
    }
    /**
     * The following line doesn't work when the plugin 
     * is used inside jquery tabs, then you should
     * add manually this piece of code inside
     * the tabs initialization where ("#myTable") is 
     * your table id selector 
     * ej: $("#myTable").dataTable().fnAdjustColumnSizing();
     */

    tableObject.fnAdjustColumnSizing();
}

插件电话:

"fnInitComplete": function () { 
    /**
     * Go to plugin definition for
     * instructions on how to use.
     */ 
    this.fnHideEmptyColumns(this);
}

如果您对代码有一些观察,请礼貌,这不是关于如何为jQuery dataTables插件隐藏空列的最后一句话。

4 个答案:

答案 0 :(得分:0)

这是一种处理此问题的方法吗?基于一次抓取所有列,并过滤行为空的位置。如果全部为空,则隐藏列。

可以添加到您编写的功能中。喜欢尝试速度测试。

//get how many columns there are
var columnCount = $('yourTable tr:first > td').length;

for(var x=0;x<columnCount;x++){
    var $columnRows = $("yourTable tbody td:nth-child(" + x + ")");
    if($columnRows.length < 0)
    {
        var $filteredRows = $columnRows.filter(function() { return $(this).html() != ""; } //only return rows where this column value is not empty
        if($filterdRows.length < 1)
        {
            $("yourTable tr td:nth-child(x)");    
        }

    }
}

请告诉我你的想法。

答案 1 :(得分:0)

对于在搜索解决方案时遇到困难的人来说,有一个非常新的DataTables插件,它可以满足您的需要,并且比您的功能更具可定制性。

您可以在创建DataTable

时添加hideEmptyCols选项来激活它
$('#example-1').DataTable({
    hideEmptyCols: true
});

有关完整选项,请查看Plugin Github页面。但是,在某些用例中,可能需要手动调用$("#example-1").DataTables().fnAdjustColumnSizing();,因为当其他用户被隐藏时,列会变得更宽。

答案 2 :(得分:0)

在找到修复问题的代码之前,我尝试了很多解决方案 - 我使用&#34; fnDrawCallback&#34;用&#34; api&#34;变量来访问columns()函数。我还希望将表格中的第一列保持为空,因为我使用一些CSS来更改表格外观。

   $(document).ready(function(){
table = $("#tableofproducts").DataTable({
                "dom": '<"top"<"left"l>pf<"clear">>rt<"bottom"ip<"clear">>',
                "oLanguage": {
                    "sSearch": "Search in table"
                },
                responsive: true,
                "processing": true,
                'ajax': {
                    'url': '<%=ResolveUrl("~/GenericHendler/SearchResultHandler.ashx")%>'
                },
                "fnDrawCallback": function () {
                    $("#loading").hide();
                    var api = this.api();
                    setTimeout( function () {
                        api.columns().flatten().each(function (colIdx) {
                            var columnData = api.columns(colIdx).data().join('');
                            if (columnData.length == (api.rows().count() - 1) && colIdx != 0) {
                                api.column(colIdx).visible(false);
                            }
                        });
                    },0)
                }
            });
})

答案 3 :(得分:0)

如果有人在寻找解决方案的过程中找到了这一点,我们找到了一条不同的路线。

我们开始研究此问题,因为我们有几组数据,其中标题基本上是除标题之外的空白行。它基本上从静态表开始发展了一段时间,让它增长了一个月或两个月,而之后又不得不添加排序/搜索功能。因此,当我们按字母顺序排序时,组标题或标题处理不正确。

我们最终得到的结果是通过使用RowGroup扩展来替换空列:https://datatables.net/extensions/rowgroup/examples/initialisation/simple.html

虽然我确定这并不适用于所有搜索此内容的人,但希望它对将来从Google登陆到这里的人有所帮助。