2013-04-18 30 views
1

我想要這個函數添加從窗體輸入的兩個值,而不是添加合併值的值。如果我輸入2和2它來到22,而我想輸出4。我認爲for循環不是wodkingFor Loop不能正常工作

<script> 
var calculate = function(){ 
var input = document.getElementsByTagName("input"); 
var length = input.length; 
for (var i = 0; i < length; i++) { 
    input[i] = input[i].value; 
    input[i] = parseInt(input[i]); 
} 
var total_living_room = input[0] + input[1]; 
document.getElementById("sh").innerHTML=total_living_room; 
} 
</script> 
+1

'輸入[0]'和'輸入[1]'仍然是一個元素,並且必須通過'parseInt函數添加值(輸入[0]。價值)+ parseInt函數(輸入[1] .value)' – Pandian

回答

5

的問題是,即getElementsByTagName()返回一個節點列表和無陣列(參見,例如,MDN on this)。

兩者在許多方面都有相似之處,但NodeList的元素無法按照您的方式進行更改。

作爲一種解決方案解析中的第二陣列的值,並使用該:

<script> 
var calculate = function(){ 
    var input = document.getElementsByTagName("input"), 
     length = input.length, 
     inputVals = []; 
    for (var i = 0; i < length; i++) { 
    inputVals.push(parseInt(input[i].value, 10)); 
    } 
    var total_living_room = inputVals[0] + inputVals[1]; 
    document.getElementById("sh").innerHTML=total_living_room; 
} 
</script> 

EDIT

Example Fiddle

+0

由於parseInt可能會返回NaN .....我建議'parseInt(input [i] .value)|| 0' – loxxy

+0

請問您可以發送一個工作jsfiddle。 – user2197789

+3

@ user2197789你不能自己複製粘貼代碼? – JJJ

1

你爲什麼要用它攜帶的值覆蓋數組中的輸入dom元素?更改爲:

var cache = []; 
for (var i = 0; i < length; i++) { 
    cache.push(parseInt(input[i].value, 10)); 
} 
0

在代碼input[0]input[1]仍然是一個元素和您必須添加如下值:

parseInt(input[0].value) + parseInt(input[1].value) 

小提琴:http://jsfiddle.net/RYh7U/145/