如果div.count
少于三个ul.elements
,如何删除li
?
html:
<ul class="list">
<li class="element level-1">
<div class="top">
<div class="content">dsssd</div>
<div class="count"></div>
<ul class="elements">
<li class="element level-2">
<div class="parent">
<div class="content">assd</div>
<ul class="elements">
<li class="element level-3">
<div id="dssd">
<div class="content">dssd</div>
</div>
</li>
<li class="element level-3">
<div id="fddd">
<div class="content">gfddg</div>
</div>
</li>
<li class="element level-3">
<div id="fdff">
<div class="content">ddee</div>
</div>
</li>
<li class="element level-3">
<div id="gfgggf">
<div class="content">hghg</div>
</div>
</li>
</ul>
</div>
</li>
<li class="element level-2">
<div id="gfgf" class="parent">
<div class="content">eeer</div>
</div>
</li>
</ul>
</div>
</li>
<li class="element level-1">
<div id="hjjh" class="top">
<div class="content">hjhj</div>
<div class="count"></div>
<ul class="elements">
<li class="element level-2">
<div id="yuyuu" class="parent">
<div class="content">uyyu</div>
<ul class="elements">
<li class="element level-3">
<div id="trtrrt">
<div class="content">trtrtr</div>
</div>
</li>
</ul>
</div>
</li>
<li class="element level-2">
<div id="opop" class="parent">
<div class="content">opop</div>
</div>
</li>
<li class="element level-2">
<div id="kjkj" class="parent">
<div class="content">kjkj</div>
</div>
</li>
</ul>
</div>
</li>
<li class="element level-1">
<div id="qwwq" class="top">
<div class="content">qwqw</div>
<div class="count"></div>
<ul class="elements">
<li class="element level-2">
<div id="ytty" class="parent">
<div class="content">tyty</div>
<ul class="elements">
<li class="element level-3">
<div id="ghghgh">
<div class="content">jhhj</div>
</div>
</li>
</ul>
</div>
</li>
</ul>
</div>
</li>
</ul>
脚本:
$('.list .count').text(function() {
var length = $(this).closest('.count')
.next('.elements')
.find('.element')
.length
;
if (length > 2) {
return length;
}
});
的CSS:
.elements {
clear: both;
}
.level-1 {
margin-bottom: 10px;
}
.count {
background-color: pink; float: left; padding: 5px;
}
答案 0 :(得分:3)
$('div.count').find('ul.elements').filter(function() {
return $(this).children('li').length < 3;
})
.end().remove();
修改强>
以下内容适用于更新的标记:
$('div.count').each(function() {
var that = $(this),
upUL = that.next('ul.elements');
upUL.add( upUL.find('ul.elements') ).filter(function() {
return $(this).children('li').length < 3;
}).length === 0 || that.remove();
});
答案 1 :(得分:1)
只需添加$(this).remove()
即可删除现有text()
函数中其他部分中的div,如下所示:
if (length > 2) {
return length;
}
else {
$(this).remove(); // less than 3 remove it
}
或添加另一个if:
if (length < 3) {
$(this).remove();
}
答案 2 :(得分:0)
选择答案的替代方案:而不是删除&#34;计数&#34;完全(如果您以后使用JavaScript实时更新这些列表的内容),为什么不隐藏它呢?然后,如果length
情况发生变化,您可以再次显示它。
这似乎有效:
$('.list .count').text(function() {
var length = $(this)
.closest('.count')
.next('.elements')
.find('.element')
.length;
if (length > 2) {
return length;
} else {
$(this).closest('.count').hide();
}
});