繁体   English   中英

如果子div为空,则删除父div

[英]Remove the parent div if child div is empty

我正在尝试删除整个父div,如果它没有wc-gallery类。 我在脚本中所拥有的与我所需要的相反。 基本上,它隐藏了所有带有wc-gallery的东西。

脚本:

// Additional Scripts
$(window).load( function() { 
    $(".gallery-container2 .gallery-item .wc-gallery").hide();
});
$(".gallery-container2 p").click(function() {
    var id = $(this).data('id');
    $("[data-id=" + id + "].gallery-item .wc-gallery").toggle()
});


$(function(){
    $(".gallery-item").each(function(){
        $(this).children('.wc-gallery').parents('.gallery-container2').hide();
    });
});

基本上,如果我隐藏所有容器并在此后显示子div,尽管我的内容由于脚本冲突而无法呈现,但这将很好地工作。 解决此问题的唯一方法是先加载所有容器,然后hide()remove()

脚本:(由于加载内容呈现而引起的冲突)

$('.gallery-container2').hide();
$(function(){
    $(".gallery-item").each(function(){
        $(this).children('.wc-gallery').parents('.gallery-container2').show();
    });
});

HTML :(第一组是应该可见的第二组是需要删除或隐藏的组。)

<ul>
    <li><div class="gallery-container2">
        <p data-id="1723"><strong>some text</strong></p>
        <div class="gallery-item" data-id="1723">
            <div class="wc-gallery" style="display: none;"></div>
        </div>
    </div></li>
    <li><div class="gallery-container2">
        <p data-id="2455"><strong>View before and after</strong></p>
        <strong></strong>
        <div class="gallery-item" data-id="2455">
            <div><div></div></div>
        </div>
    </div></li>
</ul>

遍历“ .gallery-container2”元素,并确定其是否具有“ .wc-gallery”子元素。 如果没有隐藏元素。

$('.gallery-container2').each(function(){
    var $this = $(this);

    //find element with 'wc-gallery' class
    var hasGallery = $this.find('.wc-gallery').length > 0;

    if(!hasGallery){
        $this.hide();
    }
});

用ES6术语,您可能会喜欢纯JS。

 var divsToHide = document.querySelectorAll("div div :not(.wc-gallery)"); for (var div of divsToHide) div.parentElement.parentElement.style.display = "none"; 
 <div class="gallery-container2"> <p data-id="1723"><strong>some text</strong> </p> <div class="gallery-item" data-id="1723"> <div class="wc-gallery">first container</div> </div> </div> <div class="gallery-container2"> <p data-id="1724"><strong>some text</strong> </p> <div class="gallery-item" data-id="1724"> <div> <div>second container</div> </div> </div> </div> 

尝试这个。 如果div有.wc-gallery类的子级,则它将显示父级,否则将隐藏父级。

$(function () {
   $(".gallery-item").each(function () {
     if($(this).children('.wc-gallery').length > 0)
       $(this).parents('.gallery-container2').show();
     else
       $(this).parents('.gallery-container2').hide();
    });
});

暂无
暂无

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

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