console.log在变量上给出undefined

时间:2016-07-01 23:04:55

标签: javascript jquery html javascript-events

我有一个计时器功能(它计算在给定时间内读取了多少单词,但我的代码不起作用(它表示“未捕获的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>

JAVASCRIPT

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';
    }
  });

3 个答案:

答案 0 :(得分:1)

我认为startTime没有定义,因为它是jQuery的局部变量('#start')。点击。尝试定义startTime upper

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

答案 1 :(得分:0)

在jsfiddle上运行它并且运行正常:

https://jsfiddle.net/d3eqmbv5/

只需删除:

function runTest(){

我做了一个假的wordCount函数用于测试目的。

答案 2 :(得分:0)

如果你看一下这个jsfiddle和磁带F12,首先缺少一个括号,那么下一步又是什么呢?在整个代码块之后或结束时关闭函数?

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

https://jsfiddle.net/qugp3fot/