Jquery:隐藏空表行

时间:2012-11-08 05:57:58

标签: javascript jquery html html-table tablerow

我正在尝试编写一个脚本来检测表td是否为空,如果它们隐藏了父tr

我搜索了Stack Overflow并发现了其他脚本,但似乎没有一个适用于我。

到目前为止,我有:

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

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

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

    });

但是无法让它发挥作用。任何建议将不胜感激!

小提琴:http://jsfiddle.net/MeltingDog/S8CUa/1/

6 个答案:

答案 0 :(得分:4)

试试这个 -

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

Demo

答案 1 :(得分:3)

你应该试试这个。

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

答案 2 :(得分:1)

.html()仅返回第一个匹配元素的内容,因此如果您的行有多个单元格,则无效。 .text()可能是一个更好的解决方案,除非您在单元格中有图像或其他空标记。

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

DEMO

答案 3 :(得分:1)

您似乎想要隐藏只有空格内容的行(但是单元格可能包含其他元素子节点)。使用普通的javascript:

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

助手:

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;
  }
} 

答案 4 :(得分:0)

$('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');

});

答案 5 :(得分:0)

隐藏表(如果使用jquery的表没有行)

dropdown-menu