各クラスの数を数えて 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
変数が実行されていないため、変数の使用方法に関係していることはわかっていますが、これを機能させるための最良の方法は何ですか?