我正在尝试从n输入字段添加值,但我得到的结果为NaN 哪里出错了
<table>
<tr>
<td><input class="one" name="" value="1" type="text"></td>
<td><input class="two" name="" value="2" type="text"></td>
<td><input class="three" name="" value="3" type="text"></td>
<td><input class="four" name="" value="4" type="text"></td>
<td class="total"> </td>
</tr>
</table>
<script>
var tdsOne = document.getElementsByClassName("one").value;
var tdsTwo = document.getElementsByClassName("two").value;
var tdsThree = document.getElementsByClassName("three").value;
var tdsFour = document.getElementsByClassName("four").value;
var sum = 0;
sum += tdsOne + tdsTwo + tdsThree + tdsFour;
console.log(sum);
document.getElementsByClassName('total')[0].textContent = sum;
</script>
答案 0 :(得分:1)
由于document.getElementsByClassName
是一个类似数组的对象,你需要通过它的索引来引用它
var tdsOne = document.getElementsByClassName("one")[0].value;
var tdsTwo = document.getElementsByClassName("two")[0].value;
var tdsThree = document.getElementsByClassName("three")[0].value;
var tdsFour = document.getElementsByClassName("four")[0].value;
修改强>
如果您正在寻找算术加法,则需要将这些值转换为数字。您可以使用Unary plus运算符
sum += +tdsOne + +tdsTwo + +tdsThree + +tdsFour;