Hiding a table column if the containing cells are empty with jQuery

前端 未结 3 653
别跟我提以往
别跟我提以往 2021-01-01 01:31

I have a table of the following kind:



        
                      
相关标签:
3条回答
  • 2021-01-01 02:13

    I created a version that maybe perform a little better than using a lot of CSS3 selectors in jQuery.

    $(function () {
        var $table = $('#mytable'),
            $thead = $table.find('thead'),
            $tbody = $table.find('tbody');
    
        var isEmpty = {};
        $tbody.find('td').each(function () {
    
            var $this = $(this);
            if ( $this.text() == '' && isEmpty[ $this.index() ] != false ) {
                isEmpty[ $this.index() ] = true;
            } else {
                isEmpty[ $this.index() ] = false;
            }
    
        });
    
        for (var x in isEmpty) {
            if ( isEmpty[x] ) {
                $thead.find('th').eq( x ).remove();
                $tbody.find('td:nth-child(' + (parseInt(x, 10) + 1) + ')').remove();
            }
        }
    });
    
    0 讨论(0)
  • 2021-01-01 02:13

    I would recommend adding a class to each th and td (something like "col_1", "col_2" etc) and using $("td").children("span:empty") to find the columns that should be hidden.

    0 讨论(0)
  • 2021-01-01 02:29

    This should work:

    $(document).ready(function() {
        hideEmptyCols($("#mytable"));
    });
    
    function hideEmptyCols(table) {
        //count # of columns
        var numCols = $("th", table).length;
        for ( var i=1; i<=numCols; i++ ) {
            var empty = true;
            //grab all the <td>'s of the column at i
            $("td:nth-child(" + i + ")", table).each(function(index, el) {
                //check if the <span> of this <td> is empty
                if ( $("span", el).text() != "" ) {
                    empty = false;
                    return false; //break out of each() early
                }
            });
            if ( empty ) {
                $("td:nth-child(" + i + ")", table).hide(); //hide <td>'s
                $("th:nth-child(" + i + ")", table).hide(); //hide header <th>
            }
        }
    }
    

    Or (simpler):

    function hideEmptyCols(table) {
        var rows = $("tr", table).length-1;
        var numCols = $("th", table).length;
        for ( var i=1; i<=numCols; i++ ) {
            if ( $("span:empty", $("td:nth-child(" + i + ")", table)).length == rows ) {
                $("td:nth-child(" + i + ")", table).hide(); //hide <td>'s
                $("th:nth-child(" + i + ")", table).hide(); //hide header <th>
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题