2016-08-02 28 views
1

這是我在它應該得到player1scorelist每個孩子和子節點返回數字的總和scripts.js中Javascript未正確彙總?

var player1score = 0; 
if (currentPlayer === 1) { 
    $("ul#player1scorelist").each(function() { 
     player1score = parseInt(player1score) + parseInt($(this).text()); 
    }); 
    $("#player1totalscore").text(player1score); 

    // ... 
} 

。相反,它結合了2個數字。

例如:

顯示爲356

上運行player1score一個typeof運算表示整數。

我在做什麼錯?

+0

你能提供的代碼在片段? – Owen

+5

第一件事,不要使用沒有基數的'parseInt'超載。其次'ul#player1scorelist'不能有每個循環。 ID應該是唯一的。你的意思是'ul#player1scorelist li' – naveen

+0

我不知道是什麼導致了你的具體問題,但是:1)不要在'player1score'上調用'parseInt' - 它已經是一個整數2)不要調用'parseInt'沒有基數參數(谷歌文檔)3)調用'.each'在一個用'#'選擇器創建的集合是沒用的 - 一個'#'選擇器只會產生1個元素(如果它發現任何東西根本沒有) – JAAulde

回答

4

您的問題是解析包含三個數字的父元素的文本。結果文本是3個看起來像一個整數的數字。例如:

$('<ul><li>3</li><li>5</li><li>6</li></ul>').text() // = "356" 

確保您在實際包含要總結其他評論者,例如,作爲建議的數字元素循環

$("ul#player1scorelist li").each(...) 
+2

啊,正確的問題。咄。 :)很好的捕獲。工作小提琴。 https://jsfiddle.net/7af9rLfj/1/ – naveen

+0

好抓,做得好 – JAAulde

0

你的問題是解析父元素即UL,讓您獲得UL,即356的所有值可以使用和一些其他的方式

var sum = $('#player1scorelist li').toArray().reduce(function(sum,element) {       
    return sum + Number(element.innerHTML); 
}, 0);