【发布时间】:2015-07-12 15:41:20
【问题描述】:
我有 5 个输入,其中包含价格。第六个输入将通过将前五个输入的价格相加来显示总价格。
function calculateTotal(){
var priceInputs = document.querySelectorAll("input[name^='tPriceInput']");
var totalPrice = 0;
for(var i = 0; i < priceInputs.length; i++){
totalPrice = totalPrice + parseInt(priceInputs[i].value);
}
return totalPrice;
}
上面的函数总是返回 NaN... 为什么这不起作用?我也尝试过不使用 parseInt 方法,但这只会将字符串添加在一起。
【问题讨论】:
-
你能在 jdfiddle 中分享你的 html
-
w3schools.com/jsref/jsref_parseint.aspParseInt,如果不能返回数字,则返回NaN。这意味着 priceInputs[i].value 不是数字,所以您的问题很可能在于
document.querySelectorAll("input[name^='tPriceInput']"),您认为可能是因为您输入了^=而不是=吗? -
你的代码对我来说很好:jsfiddle.net/9sjbx0s4 - - 你的问题必须在你的代码中的其他地方,或者你只向我们展示了整个代码的 sn-p。
-
我会推测您希望显示值的第 6 个字段也具有名称
tPriceInput,这导致它的空白值被添加到您的totalValue,导致 NaN。 -
专业提示,你可以说
totalPrice += parseInt(priceInputs[i].value);
标签: javascript