为什么此代码会将spentScores
作为NaN返回?
$(document).ready(initScores());
var lvlScores = 0;
var currentScores = 0;
var spentScores = 0;
function initScores() {
console.log(spentScores);
console.log(spentScores + 44);
console.log(lvlScores);
initLvlScores();
initSpentScores();
initCurrentScores();
}
function recountLvlScores() {
initScores();
clearStatistics();
}
function initLvlScores() {
var lvl = parseInt($('.lvl-select').val());
switch (lvl) {
case 1:
lvlScores = 1000;
break;
case 2:
lvlScores = 1200;
break;
case 3:
lvlScores = 1500;
break;
case 4:
lvlScores = 2000;
break;
case 5:
lvlScores = 3000;
break;
}
}
function initSpentScores() {
$('.statistics').each(function() {
console.log("!!" + spentScores + parseInt($(this).val()));
console.log("!!" + parseInt($(this).val()));
spentScores = spentScores + parseInt($(this).val());
});
}
function initCurrentScores() {
currentScores = lvlScores - spentScores;
$('.scores').html(currentScores);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
&#13;
控制台:
scoresEditCounting.js:9 undefined
scoresEditCounting.js:10 NaN
scoresEditCounting.js:11 undefined
scoresEditCounting.js:40 !!undefined44
scoresEditCounting.js:41 !!44
scoresEditCounting.js:40 !!NaN44
scoresEditCounting.js:41 !!44
答案 0 :(得分:4)
更新此行:
$(document).ready(initScores());
对此:
$(document).ready(initScores);
您希望页面在准备就绪时调用该函数。否则,您将尝试在页面准备好之前访问DOM元素。