我有这个简短的菜单:
<ul>
<li class="voucher">
Holidays (<span data="0" class="counter" id="119">0</span>)
<ul id="menu2">
<li class="voucher">
Travel deals (<span data="119" class="counter" id="123">1</span>)
</li>
<li class="voucher">
Hotel offers (<span data="119" class="counter" id="120">2</span>)
</li>
<li class="voucher">
Villas offers(<span data="119" class="counter" id="121">1</span>)
</li>
</ul>
</li>
</ul>
这个js必须收集()中的所有子类别值,并将该总和作为(值)添加到主类别假期:
var sum = 0;
$('.counter').each(function () {
var counter = $(this).html();
var id = $(this).attr('id');
if (counter == 0) {
// here I want to find and sum all values in ( ) for span that has attr data equal to 119 which is the id of the main category Holidays
sum += parseInt($('span').find("[data='" + id + "']").html(), 10) || 0;
alert(sum);
//here I want the sum of all subcategories -Holidays ( 4 )
$(this).html(sum);
}
});
但它不起作用..没有错误,只是总和不正确并且总是返回0 如果你对JS没问题,请帮忙解决这个问题,
这是jsfiddle: http://jsfiddle.net/europe77/w1uL5a8o/1/
答案 0 :(得分:3)
您正在尝试通过span对象中的data属性进行查找。您需要使用:
parseInt($("span[data='" + id + "']").html());
还有其他问题需要解决。以下是完整的工作代码:
var sum = 0;
$('.counter').each(function () {
var counter = $(this).html();
var id = $(this).attr('id');
sum += parseInt($(this).html(), 10) || 0;
});
alert(sum);
$('.counter:eq(0)').html(sum);
<强> Working Demo 强>