如果子 div 为空,则隐藏父 div

迈克·S·罗斯克兰斯

我有这三列行,并想隐藏两个空列。

<div class="wp-block-columns">
   <div class="wp-block-column">
      <div class="wp-block-image">content</div>
      <div class="tb-field">content</div>
      <div class="tb-field">content</div>
      <div class="tb-button>content</div>
   </div>
   
   <div class="wp-block-column">
      <div class="wp-block-image"> </div>
      <div class="tb-field"> </div>
      <div class="tb-field"> </div>
      <div class="tb-button> </div>
   </div>

   <div class="wp-block-column">
      <div class="wp-block-image"> </div>
      <div class="tb-field"> </div>
      <div class="tb-field"> </div>
      <div class="tb-button> </div>
   </div>

</div>

我尝试了这个和其他一些变化,但没有任何运气。

jQuery('.wp-block-column') // find the parent
.hide() // hide it
.find('> div:not(:empty)') // find child divs that are not empty
.each(function() { // use each in order to prevent errors when set is empty

jQuery(this).parent().show(); // show the parent of this non-empty element
return false; // stop processing this each
})
    ;
菲尔

我无法了解您的代码如何无法按您的意愿工作。我只注意到我必须修复 div.tb-button 标签的 html。它需要结束双引号。

话虽如此,为什么不尝试针对文本的修剪版本进行测试,看看它是否为空。它将更少地横向 DOM 并且更快,管理更少的代码。

jQuery('.wp-block-column').each(function () {
    var $this = jQuery(this);
    $this.text().trim() === '' && $this.remove();
});

如果愿意,您可以将“remove”(从 DOM 中删除元素)替换为“hide”(在元素上显示:“none”)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章