我想计算容器内的总div数,并用这样的结构切换它们的可见性.另请注意,div.content也可能驻留在另一个嵌套或嵌套嵌套的容器中.这就是为什么我用jquery处理它为每个最顶层的父容器添加div.topmost:
<div id="parent">
<div class="counter">There are 3 div.contents inside the container below</div>
<div class="container">
<div class="content"> 1 </div>
<div class="container"> <!--container inside container -->
<div class="content"> 2 </div>
<div class="content"> 3 </div>
</div>
</div>
<div class="counter">There are 5 div.contents inside the container below</div>
<div class="container">
<div class="content"> 1 </div>
<div class="content"> 2 </div>
<div class="content"> 3 </div>
<div class="content"> 4 </div>
<div class="content"> 5 </div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
和jquery:
// only grab the top most container
$('#parent > .container').addClass('topmost');
var topMost = $(".topmost");
var totContent = topMost.children('.content').size();
if (topMost.length > 0) {
topMost.before('<div class="toggle">There are ' + totContent + ' div.contents inside the container below</div>');
}
topMost.hide();
$('#parent > .counter').click(function() {
$(this).next('.topmost').toggle();
//alert(totContent);
return false;
});
Run Code Online (Sandbox Code Playgroud)
但我不能让它为每个div.counter循环.计数器始终显示所有div.content.因此怀疑放置每个功能是个问题.
任何肝脏都会非常感激.
谢谢
尝试:
// only grab the top most container
$('#parent > .container').addClass('topmost');
var topMost = $(".topmost");
topMost.each(function(){
var totContent = $(this).find('.content').size();
if (totContent > 0) {
$(this).before('<div class="toggle">There are ' + totContent + ' div.contents inside the container below</div>');
}
})
topMost.hide();
$('#parent > .counter').click(function() {
$(this).next('.topmost').toggle();
//alert(totContent);
return false;
});
Run Code Online (Sandbox Code Playgroud)