Javascript jQuery统计列表中每个项目的总数
我有下面的代码,我想计算每个类的数量,并在mytotal中显示它Javascript jQuery统计列表中每个项目的总数,javascript,jquery,variables,count,Javascript,Jquery,Variables,Count,我有下面的代码,我想计算每个类的数量,并在mytotal中显示它 <ul> <li class="myid-1">AAA</li> <li class="myid-1">AAA</li> <li class="myid-2">BBB</li> <li class="myid-1">AAA</li> </ul> <div id="mytota
<ul>
<li class="myid-1">AAA</li>
<li class="myid-1">AAA</li>
<li class="myid-2">BBB</li>
<li class="myid-1">AAA</li>
</ul>
<div id="mytotal">
<span id="item-1">AAA</span>
<span id="item-2">BBB</span>
<span id="item-3">CCC</span>
</div>
<script>
var id = '';
var cnt = '';
$('li').each(function (index, value) {
id = jQuery(this).attr('class') || '';
id = id.replace(/myid-/, '');
var cnt = jQuery("li.myid-" + id).length;
});
$('#mytotal span').each(function (index, value) {
id = jQuery(this).attr('id') || '';
id = id.replace(/aaa-/, '');
jQuery("#aaa-" + id).append(' (' + cnt + ')');
});
</script>
然而,我得到
AAA
BBB
CCC
我知道这与我使用变量的方式有关,因为变量没有执行,什么是使其工作的最佳方式?换个角度思考。您正在循环两次,这是不必要的,您设置了
cnt
,这是在局部变量上设置的,并且您不跟踪每个变量的cnt。因此,在目标中循环,选择id部分,检查对应li对应部分的长度,并相应地设置它自己的文本。另外,您可以避免处理已计算长度的相同li
$('#mytotal').children().text(function(_, cur){ //.text takes a function arg which is equivalent to doing a loop. cur represents the current test
var id = this.id.replace(/item-/, ''); //get the part from id
return cur + "(" + $("li.myid-" + id).length + ")"; //return the new text with old text + the length
});
使用JavaScript对象,您可以将文本名称设置为对象中的键,然后在迭代列表时增加键
var results = {};
var spans = $('#mytotal span').each(function(){
results[$(this).text()] = 0;
});
$('li').each(function(){
results[$(this).text()]++;
});
spans.each(function(){
var el = $(this);
id = el.attr('id') || '';
id = id.replace(/aaa-/, '');
jQuery("#aaa-" + id).append(' (' + results[el.text()] + ')');
});
你为什么要多次查找它们,这是毫无道理的
cnt
是第一个$('li')中的一个局部变量。每个(…
+1,很好的一个bruv!:)
返回cur+”(“++$(.li.myid-“+id.length+”):P
@Tats\u innit谢谢:)
var results = {};
var spans = $('#mytotal span').each(function(){
results[$(this).text()] = 0;
});
$('li').each(function(){
results[$(this).text()]++;
});
spans.each(function(){
var el = $(this);
id = el.attr('id') || '';
id = id.replace(/aaa-/, '');
jQuery("#aaa-" + id).append(' (' + results[el.text()] + ')');
});