make sum of counts of item descendants in jQuery
Hi I have the following code
<ul id="sample-menu-1" class="sf-menu">
<li class="current"><a href="#a">main item <span class="cntnews">0</span></a>
<ul>
<li><a href="#ab">sub item 1 <span class="cntnews">0</span></a>
<ul>
<li><a href="#">menu item <span class="cntnews">4</span></a></li>
<li><a href="#aba">menu item <span class="cntnews">8</span></a></li>
<li><a href="#"> sub item 2<span class="cntnews">0</span></a>
<ul>
<li><a href="#">menu item <span class="cntnews">6</span></a></li>
<li><a href="#">menu item <span class="cntnews">8</span></a></li>
</ul>
</li>
</ul>
</li>
</ul>
What I would like to do in my jQuery script is have the <span class="cntnews">开发者_运维问答;0</a>
have the sum of these items of there descendants
so for mainitem this will be 26, for sub item 1 this will be 26, and for subitem 2 this will be 14
I would like this to work for any unordered list. So far im not getting the result I want so any help would be appreciated
jQuery.fn.calcSum = function() {
var total = 0;
this.find('span.cntnews').each(function(){
total += +jQuery.text([this]);
}).eq(0).text(total);
return total;
};
Usage:
jQuery('#sample-menu-1').calcSum(); // => 26
I would do it like this:
<!doctype html>
<html>
<head>
<title></title>
<style type="text/css">
</style>
</head>
<body>
<ul id="sample-menu-1" class="sf-menu">
<li class="current"><a href="#a">main item <span class="cntnews">0</span></a>
<ul>
<li><a href="#ab">sub item 1 <span class="cntnews">0</span></a>
<ul>
<li><a href="#">menu item <span class="cntnews">4</span></a></li>
<li><a href="#aba">menu item <span class="cntnews">8</span></a></li>
<li><a href="#"> sub item 2<span class="cntnews">0</span></a>
<ul>
<li><a href="#">menu item <span class="cntnews">6</span></a></li>
<li><a href="#">menu item <span class="cntnews">8</span></a></li>
</ul>
</li>
</ul>
</li>
</ul>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function() {
$('span.cntnews').each(function(i){
var total = 0;
$(this).parent().parent().find('span.cntnews').each(function(j){
total += +jQuery.text([this]); //credit to J-P for this
});
$(this).text(total);
});
})
</script>
</body>
</html>
精彩评论