我得到了这段代码:
$(document).ready(function () {
$('.parent >' + '.child').each(function() {
console.log($(this).length);
});
});
我正在尝试记录child
类中有多少parent
个类。
这就是我的html代码:
<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
预期输出:
5
实际输出:
1
1
1
1
1
答案 0 :(得分:3)
它只是
var elementsLength = $('.parent > .child').length
当你迭代时,你得到每个元素的长度,这是1,因为它一次只有一个元素
<强> 编辑: 强>
我有点迷失,但基于下面的评论
$('.parent').each(function() {
var elementsLength = $(this).children('.child').length
if (elementsLength > 12) $(this).hide();
});
编辑,再次:
隐藏溢出的元素更容易
$('.parent .child:gt(12)').hide();
答案 1 :(得分:1)
您可以使用查找()和长度
执行此操作$(&#34; .parent&#34)。发现(&#34; .child&#34)。长度
如果您想在 EACH 中使用它 然后
$('.parent').find('.child').each(function(i) {
console.log(i);
if(i==12)
{
$(this).hide();
}
});
&#34; i&#34; 将是您代码中的元素编号
答案 2 :(得分:0)
使用length属性:
console.log( $('.parent >' + '.child').length);
答案 3 :(得分:0)
您可以使用此
$(document).ready(function () {
console.log($('.parent').childrens('.child').length);
});
答案 4 :(得分:0)
试试这个......
var elemlength = $('.parent .child').length;
答案 5 :(得分:0)
jQuery选择器实际上返回一个DOM元素数组,因此您可以直接在选择器上运行length:
$('.parent > .child').length; //Returns 5