2014-07-21 88 views
0

我很想知道如何(如果可能)添加顯示在div中的所有數字。添加顯示在單個div元素中的所有數字

<div> 1 <br /> 2 <br /> 3 <br /> 4 </div> 

所以,我想在div元素每一個號並添加所有這些,所以輸出將是10

謝謝!

+0

是的,這是可能的。 – elclanrs

+0

你能告訴我如何?謝謝。 –

+0

在這個特定的問題? – Mritunjay

回答

2

首先,給divid

<div id="myDiv"> 1 <br /> 2 <br /> 3 <br /> 4 </div> 

然後:

<script> 
// Take the content of the div and split it into an array 
var numbers = document.getElementById("myDiv").innerHTML.split(" <br> "); 
// Store the length of the array into a variable for repeated use in a loop 
var length = numbers.length; 
// Create a variable with zero value 
var sum = 0; 
// Iterate over the elements of the array and ... 
// keep adding them to the variable just created 
for(var i = 0; i < length; i++){ 
// Because the elements of the array are strings ... 
// Convert them to numbers with the javascript function parseInt() 
sum += parseInt(numbers[i]); 
} 
// Now your sum is ready; alert it or use it in some other way 
alert(sum); 
</script> 

DEMO

0

我嘗試這樣做。

var arr = document.getElementsByTagName('div')[0].textContent.split(' ') 

var sum = arr.reduce(function(a,b){return (+a)+(+b)}) 

console.log(sum) //prints 10