使用jQuery,我如何浏览每个嵌套的ul.item,计算LI的数量,并在该页面上的父span.someClass中返回该大小/长度?
<ul>
<li><span class="someClass">3</span>
<ul class="item" style="display:none">
<li>count me</li>
<li>count me</li>
<li>count me</li>
</ul>
</li>
<li><span class="someClass">1</span>
<ul class="item" style="display:none">
<li>count me</li>
</ul>
</li>
<li><span class="someClass">2</span>
<ul class="item" style="display:none">
<li>count me</li>
<li>count me</li>
</ul>
</li>
</ul>
答案 0 :(得分:5)
$("ul.item").each(function() {
// reusabilty
var context = $(this);
// count and populate
context.prev(".someClass").text(context.children().length);
});
如果这些.someClass
元素始终>> <{strong>> prev()
个元素之前, span
会在ul
调用中忽略prev
。在这种情况下,{{1}}中的过滤不是必要的,也是多余的。
答案 1 :(得分:3)
试试这个,
<强> Live Demo 强>
$('.someClass').each(function(){
$(this).text($(this).next('ul').find('li').length);
})
答案 2 :(得分:1)
您可以使用text
方法:
$('.someClass').text(function(){
return $(this).next().find('li').length
})
答案 3 :(得分:1)
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function() {
var count = 0;
$('ul').each(function(){
if(count != 0){
var len = $(this).find('li').length;
$(this).parent().find('.someClass').html(len);
}
count++;
})
});
</script>
</head>
<body>
<ul>
<li><span class="someClass"></span>
<ul class="item" style="display:none">
<li>count me</li>
<li>count me</li>
<li>count me</li>
</ul>
</li>
<li><span class="someClass"></span>
<ul class="item" style="display:none">
<li>count me</li>
</ul>
</li>
<li><span class="someClass"></span>
<ul class="item" style="display:none">
<li>count me</li>
<li>count me</li>
</ul>
</li>
</ul>
</body>
</html>
答案 4 :(得分:0)
$("ul.item").each(function() {
var _c = $(this);
_c.siblings("span.someClass").html(_c.children("li").length);
});
答案 5 :(得分:0)
使用jQuery遍历每个<li>
:
$(document).ready(function(){
var howMany;
// loop through every span.someClass
$('.someClass').each(function(){
// loop through every <li> within that span.someClass
$('li').each(function(){
// .index() is the current index of the $(this) object, it starts at 0, therefore .index()+1
howMany = $(this).index()+1;
});
// Write your counted <li> in your <span> with .text(), manipulate the text within the <span> tags
$(this).text(howMany);
});
});
有效吗?
答案 6 :(得分:-1)
$('#yourelementid > li').length;
这对你有用,而不是使用任何循环