gpt4 book ai didi

jquery - 计算容器内子 div 的总数

转载 作者:行者123 更新时间:2023-12-03 23:05:06 24 4
gpt4 key购买 nike

我想计算容器内的 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>

还有 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;
});

但我无法让它为每个 div.counter 循环。计数器始终显示所有 div.content。所以怀疑是each函数的放置有问题。

任何人都将非常感激。

谢谢

最佳答案

尝试:

 // 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;
});

关于jquery - 计算容器内子 div 的总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2680618/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com