[英]Hide div blocks if child p tags are empty
我正在垂直時間軸上工作,我將事件分為三類:國家事件,國際事件和ob告事件,每個事件都由同名的類指定。 div塊的結構如下:
<div class="cd-timeline__block js-cd-block">
<div class="cd-timeline__img cd-timeline__img--location js-cd-img">
<img src="img/cd-icon-location.svg" alt="Location">
</div>
<div class="cd-timeline__content js-cd-content">
<p class="National List">The Election Commission recommends to the President the disqualification of 20 AAP MLAs in Delhi</p>
<span class="cd-timeline__date">Jan. 19</span></div>
如果用戶在下拉菜單(屬於UI的一部分)中選擇“國家”事件,則Javascript函數會自動隱藏其他兩個類別事件,如下所示:
$('#newscategory').on('change', function(){
if(this.value=="Nat"){
$('.National').show();
$('.International').hide();
$('.Obituaries').hide();
}
});
但是,如果在特定日期不存在“全國性”事件,則圍繞p標簽的容器不會被隱藏。 我希望時間軸完全跳過該日期,這意味着如果p標簽被隱藏,我想使用class =“ cd-timeline__block js-cd-block”隱藏父div。 我該如何實現? 另一個問題是頁面上有數百個事件。
可以在此處找到代碼示例
使用.each
遍歷父塊,並檢查其子段落元素是否包含任何內容,如果保留,則保留它,如果子段落元素中沒有內容,則將其隱藏。
$('.cd-timeline__block.js-cd-block').each(function () {
var showElement = false;
$(this).find('p').each(function () {
var len = $.trim($(this).html()).length;
if (len > 0) {
showElement = true;
}
});
if (showElement === false) {
$(this).hide();
} else {
$(this).show();
}
});
這樣,如果至少一個p
子元素具有任何可用內容,則將出現父塊。
可以使用.toggle
, Array.some
和:empty
:
$(function() { // For each div element $('div').each(function () { // Show it only if one of its children paragraphs is non-empty $(this).toggle($(this).find('p').toArray().some(function (p) { return !$(p).is(':empty'); })); }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> div with some non empty paragraphs <p>non empty</p> <p></p> <p>non empty</p> </div> <div> div with only empty paragraphs <p></p> <p></p> <p></p> </div>
在您的情況下,用適當的(更具體的)選擇器替換$('div')
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.