我有一个带有div
元素的简单HTML结构。我想在每个父div
的子div
s中找到值的总和,但前提是父母至少有三个孩子。
这是我尝试过的,但它得到了每个div的总和:
var sum = 0;
$("div > div > div").each(function () {
sum += parseInt($(this).text(), 10);
});
console.log(sum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>
<!-- want to calculate this --->
<div>1</div>
<div>1</div>
<div>1</div>
<div>1</div>
</div>
<div>
<!-- don't want to calculate this --->
<div>1</div>
<div>1</div>
<div>1</div>
</div>
<div>
<!-- want to calculate this --->
<div>1</div>
<div>1</div>
<div>1</div>
<div>1</div>
</div>
</div>
所以在上面的例子中,我打印答案8。
答案 0 :(得分:5)
如果父母的孩子超过3个孩子,你可以检查每个div:
var sum = 0;
$("div > div > div").each(function () {
if($(this).parent().children('div').length >3){
sum += parseInt($(this).text(), 10);
}
});
console.log(sum);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>
<!-- want to calculate this --->
<div>1</div>
<div>1</div>
<div>1</div>
<div>1</div>
</div>
<div>
<!-- don't want to calculate this --->
<div>1</div>
<div>1</div>
<div>1</div>
</div>
<div>
<!-- want to calculate this --->
<div>1</div>
<div>1</div>
<div>1</div>
<div>1</div>
</div>
</div>
&#13;
答案 1 :(得分:1)
给父母一个班级,让我们暂时称它为.parent
:
var sum = 0;
$(".parent").each(function () {
if($(this).children('div').length>3){
$(this).children('div').each(function(){
sum += parseInt($(this).text(), 10);
});
}
});
console.log(sum);