1

各クラスの数を数えて 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

変数が実行されていないため、変数の使用方法に関係していることはわかっていますが、これを機能させるための最良の方法は何ですか?

4

2 に答える 2

2

Just think the other way around. You are looping twice which is unnecessary and you set cnt which is set on a local variable, and you don't keep track of cnt for each of them. So loop through your target, pick the id part and check for the length of corresponding li counterpart and set its own text accordingly. Plus you can avoid processing the same li for which the length has already been calculated.

 $('#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
});

Demo

于 2013-10-09T01:42:56.187 に答える
0

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()] + ')');
});
于 2013-10-09T01:46:31.307 に答える