您的函數在價格輸入的長度和這些價格輸入中的潛在值上均失敗。
的長度使用<=
會產生一個不存在的價格輸入「遺漏的類型錯誤:無法讀取的未定義的屬性‘值’」的錯誤
我不喜歡你的「數」,因爲你的名字不計算任何東西,所以我改變了它,以及一些變數,以使意圖清晰。
此外,諸如「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
這段代碼什麼都不做 –