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

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

I have a table of the following kind:



        
      
      
      
3条回答
  •  悲&欢浪女
    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 
's of the column at i $("td:nth-child(" + i + ")", table).each(function(index, el) { //check if the of this is empty if ( $("span", el).text() != "" ) { empty = false; return false; //break out of each() early } }); if ( empty ) { $("td:nth-child(" + i + ")", table).hide(); //hide 's $("th:nth-child(" + i + ")", table).hide(); //hide header } } }

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 
's $("th:nth-child(" + i + ")", table).hide(); //hide header } } }

提交回复
热议问题