j查询计数列表中每个项目的总数

jQuery count total of each item in list

本文关键字:项目 查询 数列 列表      更新时间:2023-09-26

我有下面的代码,我想计算每个类有多少个并将其显示在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="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 (3)
BBB (1)
CCC (0)

但是我得到了

AAA
BBB
CCC

我知道这与我使用变量的方式有关,因为它没有贯彻执行,让它工作的最佳方法是什么?

反过来想一想。您循环了两次,这是不必要的,并且您设置了cnt局部变量上设置的,并且您没有跟踪每个 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()] + ')');
});