【发布时间】:2017-03-28 19:00:45
【问题描述】:
为什么这段代码返回 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>
控制台:
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
【问题讨论】:
-
当
document已经是ready时,您的JavaScript 是否位于页面底部? -
是的,因为 // console.log("!!" + parseInt($(this).val()));返回“!!44”
-
HTML 元素在哪里
-
在 JSP 页面上
-
当您将 document.ready 移动到代码的底部,或者至少在您的变量声明之后会发生什么?编辑:你的问题可能是在变量被赋值之前函数都被调用了。
标签: javascript nan var