1

この質問の言い方がわかりません... n 番目の要素ごとに each ループを実行するスクリプトがあります。
これを変数として持っています。var nthCard = $('.card:nth-child(' + col + 'n+' + i + ')'); 次に、それを使用して .each を実行しますnthCard.each(function(i){...}

nthCardseach の後、 classを持つ の数を調べる必要があります.featured

html は次のように設定されています。

<div class="card"></div>
<div class="card featured"></div>
<div class="card"></div>
<div class="card"></div>
<div class="card"></div>
<div class="card featured"></div>

これが各ステートメントであると仮定すると、これらのカードのうち何枚がフィーチャーされているかを見つける必要があります。

私はこのようなことを試しました:console.log(nthCard.find('.featured').length);またconsole.log(nthCard.hasClass('.featured').length);、前者は戻り、後者は0戻りますundefined

切り捨てられたコードは次のとおりです。

function placeCard(col){
    var i = 0;
    for(i=1; i<= col; i++){
        var nthCard = $('.card:nth-child(' + col + 'n+' + i + ')');
        nthCard.each(function(idx){
            //do some code
        });
        console.log(nthCard.find('.featured').length);//I need to return the number of featured cards here.
    }
}
4

3 に答える 3

4

filter一致した要素:

var number = nthCard.filter('.featured').length;
于 2013-05-15T23:40:34.040 に答える
1

each ループにいる間にそれらを数えてみませんか?

function placeCard(col){
    var i = 0;
    for(i=1; i<= col; i++){
        var nthCard = $('.card:nth-child(' + col + 'n+' + i + ')');
        var count = 0;
        nthCard.each(function(idx, card){
            //do some code
            if ($(card).hasClass('featured')) {
                count += 1;
            }
        });
        console.log(count);//I need to return the number of featured cards here.
    }
}

または、より最適には:

function placeCard(col){
    var i = 0;
    for(i=1; i<= col; i++){
        var nthCard = $('.card:nth-child(' + col + 'n+' + i + ')');
        var count = 0;
        nthCard.each(function(idx, card){
            //do some code
            if (card.className === 'card featured') {
                count += 1;
            }
        });
        console.log(count);//I need to return the number of featured cards here.
    }
}
于 2013-05-15T23:44:27.070 に答える
1

試す:

console.log(nthCard.hasClass('featured'));
于 2013-05-15T23:40:48.193 に答える