【问题标题】:Passing function call to $(document).ready causes variable to be NaN将函数调用传递给 $(document).ready 导致变量为 NaN
【发布时间】: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


【解决方案1】:

更新这一行:

$(document).ready(initScores());

到这里:

$(document).ready(initScores);

您希望页面在准备好时调用该函数。否则,您将尝试在页面准备好之前访问 DOM 元素。

【讨论】:

  • 不是这样的。鉴于他的控制台日志正在运行,它正在执行
  • @Orpheus 它正在执行早期
  • @Orpheus 在页面准备好之前从 DOM 中获取一个元素。所以它会导致它失败
  • 谢谢!看来这行得通!但为什么?有什么区别?
  • 当您使用parenthesis() 时,会立即调用该函数。您想要的是将函数定义分配给事件处理程序,并在事件触发时调用它。这就是区别。
猜你喜欢
  • 2016-10-23
  • 2021-08-03
  • 2013-10-17
  • 2020-12-08
  • 2020-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多