Jquery: hiding empty table rows

邮差的信 提交于 2019-12-24 00:25:37

问题


I am trying to write a script that detects if a tables tds are empty and if they are hide the parent tr

I've searched Stack Overflow and found other scripts but none seem to work for me.

So far I have:

$(".table tr").each(function() {                           

    var cell = $(this).find('td').html();       

    if (cell == null){
    console.log('empty');
    $(this).parent().addClass('nodisplay');
    }

    });

but just can't get it working. Any advice would be appreciated!

Fiddle: http://jsfiddle.net/MeltingDog/S8CUa/1/


回答1:


.html() only returns the content of the first matched element, so if your rows have more than one cell this wouldn't work. .text() might be a better fix, unless you have images or other empty tags in the cells.

$("table tr").each(function() {        
    var cell = $.trim($(this).find('td').text());
    if (cell.length == 0){
        console.log('empty');
        $(this).addClass('nodisplay');
    }                   
});

DEMO




回答2:


Try this -

$("table tr td").each(function() {                               
    var cell = $(this);           
    if ($(cell).text().length == 0){
        console.log('empty');
        $(this).parent().addClass('nodisplay');
    }    
});

Demo




回答3:


you should try this.

jQuery(document).ready(function(e) {
    jQuery(jQuery('table tr td:empty').parents('tr')).addClass('nodisplay');
});



回答4:


It seems you want to hide rows that have only whitespace content (but the cells might have other element child nodes). Using plain javascript:

var rows = document.getElementsByTagName('tr');
var i = rows.length;
while (i--) {
  if ( !trim(getText(rows[i])) ) {
    rows[i].className += ' nodisplay';
  }
} 

Helpers:

function trim(s) {
  return s.replace(/(^\s*)|(\s*$)/g, '');
}

function getText(el) {
  if (typeof el.textContent == 'string') {
    return el.textContent;
  } else if (typeof el.innerText == 'string') {
    return el.innerText;
  }
} 



回答5:


$('table tr').each(function(){

    var hide = true;

    $('td',this).each(function(){

        if ($.trim($(this).text()) != "")
            hide = false;

    });

    if(hide)
        $(this).closest('tr').hide();
        // OR $(this).closest('tr).addClass('nodisplay');

});



回答6:


Hide table, if table have no rows using jquery

$('.tblClass').each(function(){
    if($(this).find('.rows').length == 0){
        $(this).hide();
    }
});


来源:https://stackoverflow.com/questions/13283346/jquery-hiding-empty-table-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!