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

前端 未结 3 674
别跟我提以往
别跟我提以往 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();
            }
        }
    });
    

提交回复
热议问题