我在这个计算器脚本中遇到NaN错误: 有什么想法吗?
以下是文本格式的整个html:
https://www.dropbox.com/s/i3u429bn5bjd4i9/orecalculator.txt
<script language="JavaScript">
var IDs = [22,17425,17426,1223,17428,17429,1225,17432,17433,1232,17436,17437,1229,17865,17866,21,17440,17441,1231,17444,17445,1226,17448,17449,20,17452,17453,11396,17869,17870,1227,17867,17868,18,17455,17456,1224,17459,17460,1228,17463,17464,19,17466,17467,1230,17470,17471];
function calculate(i){
while (i + 1 < IDs.length) {
var y=document.getElementById('reward');
var x=document.getElementById(IDs[i]);
y.value=parseInt(y.value)+parseInt(x.value);
i++;
}
}
</script>
答案 0 :(得分:3)
我在控制台中运行此代码并找到以下输出
document.getElementById('reward')
//output <input type="text" id="reward">
document.getElementById('reward').value
//""
parseInt(document.getElementById('reward').value)
//NaN
parseInt("")
//NaN
<强>解释强>
空字符串的parseInt为NaN
<强>解决方案强>
使用
Reward: <input type="text" id="reward" value="0">
代替
Reward: <input type="text" id="reward">
修正:JS代码
function calculate(i){
while (i + 1 < IDs.length) {
var y=document.getElementById('reward');
var x=document.getElementById(IDs[i]);
y.value=parseInt(y.value|0)+parseInt(x.value|0);
i++;
}
}
答案 1 :(得分:0)
未经测试但应该是这样的:
calculate = function (i){
var y = document.getElementById('reward');
var x = 0;
while (i + 1 < IDs.length) {
var elm = document.getElementById(IDs[i]);
x+=parseInt(elm.value||0);
i++;
}
y.value = x;
};
工作小提琴: