1

不知道如何表达这个问题...我有一个脚本,它为每个第 n 个元素执行一个循环。
我把它作为一个变量:var nthCard = $('.card:nth-child(' + col + 'n+' + i + ')'); 然后我用它做一个 .eachnthCard.each(function(i){...}

在每个之后,我需要找出有多少人nthCards有课.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

尝试:

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

为什么不在每个循环中计算它们?

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 回答