简体   繁体   English

如果子DIV为空,则显示/隐藏表行

[英]Show/hide table row if a child DIV is empty

I have a table with multiple entries. 我有一个包含多个条目的表。 After each entry table row is an edit table row, with a column spanned cell, inside of which is a DIV which HTML is dynamically loaded into. 在每个条目表行之后是一个编辑表行,其中包含一个跨越列的单元格,其中是一个动态加载HTML的DIV。 The problem is that having all these empty table rows causes a lot of extra whitespace to appear on the page when it's rendered. 问题是,拥有所有这些空表行会导致在呈现时页面上出现大量额外的空白。

I understand I can't dynamically load HTML directly into the cell, so I have a DIV in it which I load the content into. 我知道我不能直接将HTML动态加载到单元格中,所以我在其中加载了一个DIV,我将内容加载到其中。

I want to hide any table row while the child DIV in it is empty, and show that table row once information has been dynamically loaded into the child DIV. 我希望在其中的子DIV为空时隐藏任何表行,并在信息已动态加载到子DIV时显示该表行。 This dynamically loaded information can also removed so I need it to be hidden again once it's empty again. 这个动态加载的信息也可以删除,因此我需要再次将其隐藏一次。

<table width="100%">
  <tbody>
    <tr>
      <td>A</td>
      <td>B</td>
      <td>C</td>
    </tr>
    <tr style="display: none;">
      <td colspan="3"><div></div></td>
    </tr>
  </tbody>
</table>



$("tr").each(function() {
    if (this.children().filter(":empty").length) {
        this.hide();
    } else {
        this.show();
    }
});
  • The div isn't a child, it's a grandchild, thus children() won't find the div s. div不是孩子,它是孙子,因此children()不会找到div Use the context or find instead. 请改用上下文或find

  • You are operating hide and show on the DOM element, not the jQuery element. 您正在DOM元素上操作hideshow ,而不是jQuery元素。 You need to wrap it in jQuery first. 你需要先将它包装在jQuery中。

Therefore, run this code everytime you load something : 因此, 每次加载时运行此代码

//find empty divs and hide it's tr
$("div:empty").closest('tr').hide();

//find non-empty divs and show it's tr
$("div:not(:empty)").closest('tr').show();

And look ma! 看看马! No loops! 没有循环! No each ! 不是each :D :d

You should use $(this) instead of this . 你应该使用$(this)而不是this

Reason being: $(this) is a JQuery object, which allows you to call JQuery methods like .children() and .filter(":empty") on it, whereas this is only a Javascript object... 原因是: $(this)是一个JQuery对象,它允许你调用JQuery方法,如.filter(":empty") .children().filter(":empty") ,而this只是一个Javascript对象......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM