jQuery:如果所有子div的html为空,则隐藏父div [英] jQuery: hide parent div if all children div's html is empty

查看:204
本文介绍了jQuery:如果所有子div的html为空,则隐藏父div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含三个子div的父div,我想检查子div以查看它们是否为空,如果它们都为空,我想隐藏父div,以便背景在我的设计中消失./p>

I have a parent div containing three child divs, I want to check the child divs to see if they are empty, if they are all empty, I want to hide the parent div so the background goes away in my design.

<div class="main">
    <div class="tot1"></div>
    <div class="tot2"></div>
    <div class="tot3">test</div>
<div>

jQuery(".tot1:empty, .tot2:empty, .tot3:empty").parent().hide();

推荐答案

其他答案都不错,但出于性能原因,我推荐以下答案:

The other answers are good but for performance reasons I recommend this one:

$('.main').each(function () {
  var $main = $(this),
      $allChildren = $main.children();
      $allEmptyChildren = $allChildren.filter(':empty');
  $main.toggle($allChildren.length !== $allEmptyChildren.length);
});

  • 即使页面中有多个.main元素,它也可以正常工作.
  • 它缓存$(this)的值并重用查询结果以提高性能.
  • 它不再hide() .mainshow()它(以避免重新绘制).
  • 在父节点上不需要任何额外的标记.
  • 即使以后您决定将子节点从<div>更改为更具语义的内容,它也可以正常工作.
  • 当所有子项都为空时,它不仅会隐藏.main,还会在子项中包含文本时显示它们.因此,它既可以处理隐藏内容,也可以处理显示内容.您要做的就是再次运行它.
    • It works correctly even if there are multiple .main elements in a page.
    • It caches the value of $(this) and reuses the query results to boost performance.
    • It doesn't hide() the .main and show() it again (to avoid a repaint).
    • It doesn't need any extra markup on the parent node.
    • It works even if later you decide to change child nodes from <div> to something more semantic.
    • Not only it hides the .main when all children are empty, it will show them when children have text. So it handles both hiding and showing. All you have to do is to run it again.
    • 源代码非常具有解释性:它查找所有直接子代.然后找到空的.如果空子代数等于所有子代数,它将隐藏父节点(即使不使用parent()函数也是如此).这可能需要多几行代码,但是速度很快.

      The source code is quite explanatory: it finds all the immediate children. Then finds ones that are empty. If the number of empty children is equal to the number of all children it hides the parent node (without even using the parent() function). This might be a few more lines of code, but it's fast.

      尝试实时.

      这篇关于jQuery:如果所有子div的html为空,则隐藏父div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆