不确定如何说出这个问题......
我有一个脚本为每个第n个元素执行每个循环
我将此作为变量:var nthCard = $('.card:nth-child(' + col + 'n+' + i + ')');
然后我用nthCard.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.
}
}
答案 0 :(得分:4)
filter
匹配的元素:
var number = nthCard.filter('.featured').length;
答案 1 :(得分:1)
尝试:
console.log(nthCard.hasClass('featured'));
答案 2 :(得分: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.
}
}