删除/隐藏表<tr>(s) 其<td>(s) 没有文本

Remove/Hide Table <tr>(s) which Their <td>(s) Does not Have Text

本文关键字:gt lt td 文本 tr 删除 隐藏      更新时间:2023-09-26

你能看看这个演示吗?让我知道如何隐藏或删除动态表中<td>(如果一行中的所有行)为空的所有行吗?这主要发生在表的末尾,因为我生成了一个有5行的表,但有时我从数据源只得到3或4行的数据。

请注意,我所说的空是指一个文本值,而不是像div.这样的html元素

<table style="width:100%">
    <tr>
        <td class="monBox">Jill</td>
        <td class="monBox">Smith</td>
        <td class="monBox">50</td>
    </tr>
    <tr>
        <td class="monBox">Eve</td>
        <td class="monBox">Jackson</td>
        <td class="monBox">94</td>
    </tr>
    <tr>
        <td class="monBox"></td>
        <td class="monBox"></td>
        <td class="monBox"></td>
    </tr>
    <tr>
        <td class="monBox">Eve</td>
        <td class="monBox">Jackson</td>
        <td class="monBox">94</td>
    </tr>
     <tr>
        <td class="monBox"></td>
        <td class="monBox"></td>
        <td class="monBox"></td>
    </tr>   
</table>

感谢

试着遍历每个tr,并检查里面的所有td元素是否都是空的,就像一样

$('table').find('tr').each (function() {
    var rows = 0;
    var rows_empty = 0;
     $(this).find('td').each (function() {
          rows++;
          if($(this).text().trim() == "")
              rows_empty++;
    }); 
    if(rows === rows_empty)
        $(this).remove();
}); 

jsfiddle

试试这个,注意我给了表一个target:的ID

//Loop through rows with empty cells
$("#target tr").has("td:empty").each(function(){
    //hide the row if all cells are empty
    if($(this).find("td").length === $(this).find("td:empty").length){
        $(this).hide();    
   }
});

Fiddle

或者稍微简单一点:

$("#target tr").has("td:empty").each(function(){
    if($(this).find("td:not(:empty)").length === 0){
        $(this).hide();
    }
});

或者更好:

$('#target tr').not(':has(td:not(:empty))').remove();

演示

$('#target tr').each(function(index,el).   
 { 
    if($.trim($(this).text()) == '')
    {
       $(this).remove();
    }
}
);

它在不检查所有的表单元格的情况下工作