繁体   English   中英

console.log 给出未定义的变量

[英]console.log gives undefined on a variable

我有一个计时器功能(它计算在给定时间内读取了多少字,但我的代码不起作用)。

它说:

“未捕获的 ReferenceError:startTime 未定义”

在线的:

"testTime = (stopTime - startTime)/1000 + testTime;" 

HTML

<button class="btn" id="start">Start Reading</button>
  <div id="page1" style="display: block;"><p class="title">
    Text goes here
 </div>
  <button class="btn" id="stop">Finished!</button>
  <span id="wordValue"></span>
  <span id="timeValue"></span>

爪哇脚本

function runTest(){

 testRunning = false;
 restart = false;
 var testTime = 0;

 jQuery('#start').click(function(){
   startTime = new Date().getTime();
   testRunning = true;
 });

  jQuery('#stop').click(function(){

    stopTime = new Date().getTime();
    testTime = (stopTime - startTime)/1000 + testTime;


    testRunning = false;
    // set wpm =  calculated words per minute
    wpm = Math.round(wordCount('#page1') / (testTime / 60));
    // set difference = calculated difference between words per minute and     national average (250)
    difference = Math.round(100*((wpm/250)-1));
    if (difference < 0) {
      difference = difference*-1 + '% slower';
    } else {
      difference = difference+'% faster';
    }
  });

我认为 startTime 未定义,因为它是 jQuery('#start').click 的局部变量。 尝试定义 startTime 上限

var testRunning = false;
var restart = false;
var testTime = 0;
var startTime = 0; // here

在 jsfiddle 上运行它,它运行良好:

https://jsfiddle.net/d3eqmbv5/

只需要删除:

function runTest(){

为了测试目的,我制作了一个假的wordCount函数。

如果您查看此 jsfiddle 和磁带 F12,则首先缺少括号,那么下一步可以做什么? 在完整的代码块之后或结束时立即关闭函数?

function runTest(){
    testRunning = false;
    restart = false;
    var testTime = 0;

https://jsfiddle.net/qugp3fot/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM