我希望此函数将从表单输入的两个值相加,但不是相加而是合并数字。如果我输入 2 和 2,它会变成 22,而我想要输出 4。我认为 for 循环不起作用
<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>
最佳答案
问题是,getElementsByTagName()
返回一个 NodeList 而没有数组(参见,例如 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>
编辑
关于javascript - For 循环不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16080174/