您的函数在价格输入的长度和这些价格输入中的潜在值上均失败。
的长度使用<=
会产生一个不存在的价格输入“遗漏的类型错误:无法读取的未定义的属性‘值’”的错误
我不喜欢你的“数”,因为你的名字不计算任何东西,所以我改变了它,以及一些变数,以使意图清晰。
此外,诸如“08”之类的值不会按预期解析(八进制),也不会“fred”。
审议下列投入:
<input class="price" value="33" />
<input class="price" value="3" />
<input class="price" value="-23" />
<input class="price" value="13" />
<input class="price" value="08" />
<input class="price" />
<input class="price" value="fred" />
<input id="total" />
修改后的代码:
function totalPrice() {
var total = 0;
var prices = document.getElementsByClassName('price');
var len = prices.length;
for (var i = 0; i < len; i++) {
total += isNaN(parseInt(prices[i].value, 10)) ? 0 : parseInt(prices[i].value, 10);
}
document.getElementById('total').value = total;
}
totalPrice();
什么是你的错误信息? – messerbill
你是什么意思“设置循环”? https://jsfiddle.net/7msje7vr/ – Pimmol
这段代码什么都不做 –