簡體   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