2012-02-16 22 views
0

我期待總結所有文字稱爲類內部編號「發送」,但是當我提醒下面的代碼它給人的零輸出:jQuery的總和

var sum = 0;    
var thedate = $(".date:contains('15th February 2012')"); 

    $(thedate).each(function() {    
    var sents = $(this).next('.sent').text(); 

    var sentsnumb = parseFloat(sents); 

     sum += Number($(sentsnumb)); 

}); 
    alert(sum); 

這裏是我的html:

<tr> 
    <td class="date">15th February 2012</td> 
    <td class="sent"> 5</td> 
</tr> 
<tr> 
    <td class="date">15th February 2012</td> 
    <td class="sent"> 5</td> 
</tr> 
<tr> 
    <td class="date">15th February 2012</td> 
    <td class="sent"> 10</td> 
</tr> 
<tr> 
    <td class="date">15th February 2012</td> 
    <td class="sent"> 10</td> 
</tr> 

從上面的所需輸出將是數字「30」。

回答

5

試試這個方法: -

var sum = 0;    
var thedate = $(".date:contains('15th February 2012')"); 

    $(thedate).each(function() {    
    var sents = $(this).next('.sent').text(); 
    sum = sum + Number(sents); 
}); 

alert(sum);​ 

實際的問題是$(sentsnumb)。它應與sentsnumb

+1

此作品:請參閱jsfiddle:http://jsfiddle.net/uLDpM/ 您需要使用Number()函數的原因是'.text()'返回一個文本字符串。 'Number()'將文本轉換回可以總結的數值。 – 2012-02-16 17:26:24

+0

謝謝你,這工作得很好! – ToddN 2012-02-16 17:30:06

0

試試這個來代替:

var sum = 0;    
var thedate = $(".date:contains('15th February 2012')"); 

$(thedate).each(function() {    
    var sents = $(this).next('.sent').text(); 
    var sentsnumb = parseFloat(sents); 
    sum += sentsnumb; 
}); 
alert(sum); 
0

你並不需要通過jQuery的$函數傳遞的一切。

var sum = 0; 
var thedate = $(".date:contains('15th February 2012')"); 

thedate.each(function() { // `thedate` is already a jQuery object, no need for `$()` 
    var sents = $(this).next('.sent').text(); 

    var sentsnumb = parseInt(sents, 10); // use parseInt if your values don't have decimals 

    sum += sentsnumb; // sentsnum is a float, do not use `$()` (or Number) 
}); 

alert(sum);​ 

而且,你不能有一個<table>之外<tr>代碼,請確保您的HMTL是有效的。