我在侧边栏中使用列表,我想显示该列表中有多少项的标签号。
我在这里创建了一个JSFiddle http://jsfiddle.net/WRVgW/来演示列表以及我想要实现的目标。我相信这是可以通过Jquery实现的,但我不确定如何并寻找一些指导。
在我的示例中,我在数字34
中进行了硬编码,我希望根据下面的列表动态生成数字。
我评论的HTML代码粘贴在下面,但可能更容易在http://jsfiddle.net/WRVgW/
的结果中查看<div id="sidebar">
<ul class="sidebarSections">
<li class="submenu">
<a href="#"><span>Design Projects</span><!--This is the name of the project-->
<span class="label">34</span></a><!--This is the number which I want to display the number of li items below dynamically (should be 3)-->
<ul>
<li><a>Project x</a></li>
<li><a>Project y</a></li>
<li><a>Project z</a></li>
</ul>
</li>
<li class="submenu">
<a href="#"><span>Tech Projects</span><!--This is the name of the project-->
<span class="label">34</span></a><!--This is the number which I want to display the number of li items below dynamically (should be 5)-->
<ul>
<li><a>Project x</a></li>
<li><a>Project y</a></li>
<li><a>Project z</a></li>
<li><a>Project y</a></li>
<li><a>Project z</a></li>
</ul>
</li>
<li class="submenu">
<a href="#"><span>IA Projects</span><!--This is the name of the project-->
<span class="label">34</span></a><!--This is the number which I want to display the number of li items below dynamically (should be 7)-->
<ul>
<li><a>Project x</a></li>
<li><a>Project y</a></li>
<li><a>Project z</a></li>
<li><a>Project y</a></li>
<li><a>Project z</a></li>
<li><a>Project y</a></li>
<li><a>Project z</a></li>
</ul>
</li>
</ul>
答案 0 :(得分:4)
一种可能的解决方案:
$(".submenu .label").text(function() {
return $(this).closest(".submenu").find("li").length;
});
答案 1 :(得分:0)
代码(javascript)&amp; id your uls
var ul = document.getElementById("myul");
var liNodes = [];
for (var i = 0; i < ul.childNodes.length; i++) {
if (ul.childNodes[i].nodeName == "LI") {
liNodes.push(ul.childNodes[i]);
}
}
答案 2 :(得分:0)
另一个选择
$('.sidebarSections ul').each(function(){
var liCount = $(this).find('li').length;
$(this).closest('.submenu').find('span.label').text(liCount);
});