嘿,所有人都为我的工作制作一张迷你高尔夫记分卡,如果输入留空,我希望输入值自动设置为0。我以为将变量声明为0可以解决该问题,但是如果所有输入均保留为空白,则会显示“ NaN”而不是0。我对javascript
很陌生function p1Score() {
h1p1, h2p1, h3p1, h4p1, h5p1, h6p1, h7p1, h8p1, h9p1, h10p1, h11p1, h12p1, h13p1, h14p1, h15p1, h16p1, h17p1, h18p1 = 0
var h1p1 = document.getElementById( "h1p1").valueAsNumber;
var h2p1 = document.getElementById( "h2p1").valueAsNumber;
var h3p1 = document.getElementById( "h3p1").valueAsNumber;
var h4p1 = document.getElementById( "h4p1").valueAsNumber;
var h5p1 = document.getElementById( "h5p1").valueAsNumber;
var h6p1 = document.getElementById( "h6p1").valueAsNumber;
var h7p1 = document.getElementById( "h7p1").valueAsNumber;
var h8p1 = document.getElementById( "h8p1").valueAsNumber;
var h9p1 = document.getElementById( "h9p1").valueAsNumber;
var h10p1 = document.getElementById("h10p1").valueAsNumber;
var h11p1 = document.getElementById("h11p1").valueAsNumber;
var h12p1 = document.getElementById("h12p1").valueAsNumber;
var h13p1 = document.getElementById("h13p1").valueAsNumber;
var h14p1 = document.getElementById("h14p1").valueAsNumber;
var h15p1 = document.getElementById("h15p1").valueAsNumber;
var h16p1 = document.getElementById("h16p1").valueAsNumber;
var h17p1 = document.getElementById("h17p1").valueAsNumber;
var h18p1 = document.getElementById("h18p1").valueAsNumber;
var totalscorep1 = h1p1 + h2p1 + h3p1 + h4p1 + h5p1 + h6p1 + h7p1 + h8p1 + h9p1 + h10p1 + h11p1 + h12p1 + h13p1 + h14p1 + h15p1 + h16p1 + h17p1 + h18p1;
document.getElementById("p1total").innerHTML = totalscorep1;
}
答案 0 :(得分:0)
我建议您不要重复18次。问题似乎是您的某些价值观是NaN。试试看,看看哪些:
function p1Score() {
var totalScore = 0;
for(var i = 1; i <= 18; i++) {
var key = "h" + i + "p1";
var value = document.getElementById(key).valueAsNumber;
if (isNaN(value) {
console.log(key + " is NaN")
}
else {
totalScore += value;
}
}
document.getElementById("p1total").innerHTML = totalScore;
}