【问题标题】:Uncaught ReferenceError at HTMLButtonElement.onclickHTMLButtonElement.onclick 处未捕获的 ReferenceError
【发布时间】:2020-09-23 08:03:49
【问题描述】:

我有一个 html 和 js 的测验代码。测验有 10 个问题,应该有按钮可以在问题之间移动。 第一个问题很好,但是当我尝试回答第二个问题时,我在控制台中收到此错误: Game.html:1 Uncaught ReferenceError: num is not defined 在 HTMLButtonElement.onclick (Game.html:1)

我可以做些什么来防止这个错误?我试图将js代码复制到html中的脚本元素,但没有成功。

html的代码是这样的:

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Game</title>
    <script src="script.js"></script>
    <link rel="stylesheet" href="style.css">
</head>
<body id="gameBody" onload="InitGame()">

    <h1>Welcome to the game</h1>
    <h3 class="header">Your score</h3>
    <h3 class="text" id="score"></h3>
    <h5 class="header">Choose the right answer</h5>
    <p class="header">The question number</p>
    <p class="text" id="questionNumber"></p>
    <p class="header">The word you need to translate</p>
    <p id="word"></p>
    <div id="image">

    </div>
    <div id="options">

    </div>
    <p id="message"></p>
    <button class="myChoise" onclick="prevQuestion()">Previous</button>
    <button class="myChoise" onclick="nextQuestion()">Next</button>
   
</body>
</html>  ```

And in script.js I have this array of objects :

let food=[{
    'ID':1,
    'word':'What is the national dish of Italy',
    'options':[
        {name : 'פסטה, פיצה, ריזוטו'},
        {name : 'המבורגר'},
        {name : 'מרק עוף'}
    ],
    'img':'img/200.jpg',
    'rightAnswer':'פסטה, פיצה, ריזוטו',
  },
  {
    'ID':2,
    'word':'What is the national dish of the United States?',
    'options':[
        {name : 'המבורגר, נקנקיה בלחמניה, פאי '},
        {name : 'פיצה'},
        {name : 'ריזוטו'}
    ],
    'img':'img/23.jpg',
    'rightAnswer':'המבורגר, נקנקיה בלחמניה, פאי',
  },
  {
    'ID':3,
    'word':'What is the national dish of Hungary?',
    'options':[
        {name : 'גולאש'},
        {name : 'המבורגר'},
        {name : 'נקנקיה בלחמניה'}
    ],
    'img':'img/21.jpg',
    'rightAnswer':'גולאש',
  },
  {
    'ID':4,
    'word':'What is the national dish of Greece?',
    'options':[
        {name : 'מוסקה,סלט יווני'},
        {name : 'גולאש'},
        {name : 'המבורגר'}
    ],
    'img':'img/222.jpg',
    'rightAnswer':'סלט יווני,מוסקה',
  },
  {
    'ID':5,
    'word':'What is the national dish of Belarus?',
    'options':[
        {name : 'לביבה'},
        {name : 'קציצות בשר'},
        {name : 'מרק עוף'}
    ],
    'img':'img/444.jpg',
    'rightAnswer':'לביבה',
  },
  {
    'ID':6,
    'word':'What is the national dish of the United Kingdom?',
    'options':[
        {name : ' פיש אנד ציפס'},
        {name : 'ответ'},
        {name : 'название'}
    ],
    'img':'img/20.jpg',
    'rightAnswer':' פיש אנד ציפס',
  },
  {
    'ID':7,
    'word':'What is China national dish?',
    'options':[
        {name : 'אורז'},
        {name : 'קציצות בקר'},
        {name : 'המבורגר'}
    ],
    'img':'img/486.jpg',
    'rightAnswer':'אורז',
  },
  {
    'ID':8,
    'word':'What is the national dish of France?',
    'options':[
        {name : 'באגט, קרואסון, פואה גרא'},
        {name : 'נקנקיה בלחמניה'},
        {name : 'לביבות'}
    ],
    'img':'img/22.jpg',
    'rightAnswer':'באגט, קרואסון, פואה גרא',
  },
  {
    'ID':9,
    'word':'What is the national dish of Cyprus?',
    'options':[
        {name : 'חלומי'},
        {name : 'באגט'},
        {name : 'אורז'}
    ],
    'img':'img/24.jpg',
    'rightAnswer':'חלומי',
  },
  {
    'ID':10,
    'word':'What is the national dish of Mexico?',
    'options':[
        {name : 'טאקו, גואקמולי'},
        {name : 'אורז'},
        {name : 'פיש אנד ציפס'}
    ],
    'img':'img/264.jpg',
    'rightAnswer':'טאקו,גואקמולי',
  }
]


And this functions :

let score = 0;
function InitGame(){
 document.getElementById("questionNumber").innerHTML = food[0].ID;
    document.getElementById("score").innerHTML= score;
    document.getElementById("word").innerHTML= food[0].word;
    let imgSrc = food[0].img;
    let img = document.createElement("img");
    img.src = food[0].img;
    img.width = '500';
    img.height = '300';
    document.getElementById("image").appendChild(img);
    document.getElementById("options").innerHTML =
    "<button class='btn' id='1' onclick='checkAnswer(food[0].ID,this)'></button> " +
     "<button class='btn' id='2' onclick='checkAnswer(food[0].ID,this)'></button> " +
     "<button class='btn' id='3' onclick='checkAnswer(food[0].ID,this)'></button>";
    document.getElementById("options").getElementsByTagName('button')[0].innerHTML = food[0].options[0].name;
    document.getElementById("options").getElementsByTagName('button')[1].innerHTML = food[0].options[1].name;
    document.getElementById("options").getElementsByTagName('button')[2].innerHTML = food[0].options[2].name; 
}

function checkAnswer(questionNum,btn){
 for(i in food)
            {
                if(food[i].ID === questionNum)
                {
                    let chosed = btn.id;
                    let answer = food[i].options[chosed-1].name;
                    if(answer === food[i].rightAnswer)
                    {
                        score = score+1;
                        document.getElementById("score").innerHTML= score;
                        document.getElementById("message").innerHTML = "Right answer";
                        nextQuestion();
                    }
                    else
                    {
                        score = score-0.5;
                        document.getElementById("score").innerHTML= score;
                        document.getElementById("message").innerHTML = "wrong answer, please try again";
                    }
                }
            } 
}

function nextQuestion(){
   let qNum = document.getElementById("questionNumber").innerHTML;
   let num = ++qNum;
   if(num === 10)
        {
            num = 0;
        }
        document.getElementById("questionNumber").innerHTML = num;
        document.getElementById("score").innerHTML= score;
        document.getElementById("word").innerHTML= food[num].word;
        document.getElementById("image").innerHTML="";
        let imgSrc = food[num].img;
        let img = document.createElement("img");
        img.src = food[num].img;
        img.width = '500';
        img.height = '300';
        document.getElementById("image").appendChild(img);
        document.getElementById("options").innerHTML="";
        document.getElementById("options").innerHTML =
        "<button class='btn' id='1' onclick='checkAnswer(food[num].ID,this)'></button> " +
        "<button class='btn' id='2' onclick='checkAnswer(food[num].ID,this)'></button> " +
        "<button class='btn' id='3' onclick='checkAnswer(food[num].ID,this)'></button>";
        document.getElementById("options").getElementsByTagName('button')[0].innerHTML = food[num].options[0].name;
        document.getElementById("options").getElementsByTagName('button')[1].innerHTML = food[num].options[1].name;
        document.getElementById("options").getElementsByTagName('button')[2].innerHTML = food[num].options[2].name;

}


function prevQuestion(){
 let qNum = document.getElementById("questionNumber").innerHTML;
        let num = --qNum;
if(num === -1)
        {
            num = 10;
        }
        document.getElementById("questionNumber").innerHTML = num;
        document.getElementById("score").innerHTML= score;
        document.getElementById("word").innerHTML= food[num].word;
        document.getElementById("image").innerHTML="";
        let imgSrc = food[num].img;
        let img = document.createElement("img");
        img.src = food[num].img;
        img.width = '500';
        img.height = '300';
        document.getElementById("image").appendChild(img);
        document.getElementById("options").innerHTML="";
        document.getElementById("options").innerHTML =
        `<button class='btn' id='1' onclick='checkAnswer(food[num].ID,this)'></button> <button class='btn' id='2' onclick='checkAnswer(food[num].ID,this)'></button> <button class='btn' id='3' onclick='checkAnswer(food[num].ID,this)'></button>`;
        document.getElementById("options").getElementsByTagName('button')[0].innerHTML = food[num].options[0].name;
        document.getElementById("options").getElementsByTagName('button')[1].innerHTML = food[num].options[1].name;
        document.getElementById("options").getElementsByTagName('button')[2].innerHTML = food[num].options[2].name;
}

【问题讨论】:

    标签: javascript html error-handling


    【解决方案1】:

    你得到num is not defined的原因是你设置了像'checkAnswer(food[num].ID,this)'这样的内部HTML,在这种情况下,数字没有引用函数中的num变量,你应该使用'checkAnswer(food[" + num + "].ID,this)',这样当html呈现时而不是 num 它将呈现像这样的数字 checkAnswer(food[9].ID,this)

    let food = [{
        'ID': 1,
        'word': 'What is the national dish of Italy',
        'options': [{
            name: 'פסטה, פיצה, ריזוטו'
          },
          {
            name: 'המבורגר'
          },
          {
            name: 'מרק עוף'
          }
        ],
        'img': 'img/200.jpg',
        'rightAnswer': 'פסטה, פיצה, ריזוטו',
      },
      {
        'ID': 2,
        'word': 'What is the national dish of the United States?',
        'options': [{
            name: 'המבורגר, נקנקיה בלחמניה, פאי'
          },
          {
            name: 'פיצה'
          },
          {
            name: 'ריזוטו'
          }
        ],
        'img': 'img/23.jpg',
        'rightAnswer': 'המבורגר, נקנקיה בלחמניה, פאי',
      },
      {
        'ID': 3,
        'word': 'What is the national dish of Hungary?',
        'options': [{
            name: 'גולאש'
          },
          {
            name: 'המבורגר'
          },
          {
            name: 'נקנקיה בלחמניה'
          }
        ],
        'img': 'img/21.jpg',
        'rightAnswer': 'גולאש',
      },
      {
        'ID': 4,
        'word': 'What is the national dish of Greece?',
        'options': [{
            name: 'מוסקה,סלט יווני'
          },
          {
            name: 'גולאש'
          },
          {
            name: 'המבורגר'
          }
        ],
        'img': 'img/222.jpg',
        'rightAnswer': 'מוסקה,סלט יווני',
      },
      {
        'ID': 5,
        'word': 'What is the national dish of Belarus?',
        'options': [{
            name: 'לביבה'
          },
          {
            name: 'קציצות בשר'
          },
          {
            name: 'מרק עוף'
          }
        ],
        'img': 'img/444.jpg',
        'rightAnswer': 'לביבה',
      },
      {
        'ID': 6,
        'word': 'What is the national dish of the United Kingdom?',
        'options': [{
            name: ' פיש אנד ציפס'
          },
          {
            name: 'ответ'
          },
          {
            name: 'название'
          }
        ],
        'img': 'img/20.jpg',
        'rightAnswer': ' פיש אנד ציפס',
      },
      {
        'ID': 7,
        'word': 'What is China national dish?',
        'options': [{
            name: 'אורז'
          },
          {
            name: 'קציצות בקר'
          },
          {
            name: 'המבורגר'
          }
        ],
        'img': 'img/486.jpg',
        'rightAnswer': 'אורז',
      },
      {
        'ID': 8,
        'word': 'What is the national dish of France?',
        'options': [{
            name: 'באגט, קרואסון, פואה גרא'
          },
          {
            name: 'נקנקיה בלחמניה'
          },
          {
            name: 'לביבות'
          }
        ],
        'img': 'img/22.jpg',
        'rightAnswer': 'באגט, קרואסון, פואה גרא',
      },
      {
        'ID': 9,
        'word': 'What is the national dish of Cyprus?',
        'options': [{
            name: 'חלומי'
          },
          {
            name: 'באגט'
          },
          {
            name: 'אורז'
          }
        ],
        'img': 'img/24.jpg',
        'rightAnswer': 'חלומי',
      },
      {
        'ID': 10,
        'word': 'What is the national dish of Mexico?',
        'options': [{
            name: 'טאקו,גואקמולי'
          },
          {
            name: 'אורז'
          },
          {
            name: 'פיש אנד ציפס'
          }
        ],
        'img': 'img/264.jpg',
        'rightAnswer': 'טאקו,גואקמולי',
      }
    ]
    
    let score = 0;
    
    function InitGame() {
      document.getElementById("questionNumber").innerHTML = food[0].ID;
      document.getElementById("score").innerHTML = score;
      document.getElementById("word").innerHTML = food[0].word;
      let imgSrc = food[0].img;
      let img = document.createElement("img");
      img.src = food[0].img;
      img.width = '500';
      img.height = '300';
      document.getElementById("image").appendChild(img);
      document.getElementById("options").innerHTML =
        "<button class='btn' id='1' onclick='checkAnswer(food[0].ID,this)'></button> " +
        "<button class='btn' id='2' onclick='checkAnswer(food[0].ID,this)'></button> " +
        "<button class='btn' id='3' onclick='checkAnswer(food[0].ID,this)'></button>";
      document.getElementById("options").getElementsByTagName('button')[0].innerHTML = food[0].options[0].name;
      document.getElementById("options").getElementsByTagName('button')[1].innerHTML = food[0].options[1].name;
      document.getElementById("options").getElementsByTagName('button')[2].innerHTML = food[0].options[2].name;
    }
    
    function checkAnswer(questionNum, btn) {
      debugger
      for (i in food) {
        if (food[i].ID === questionNum) {
          let chosed = btn.id;
          let answer = food[i].options[chosed - 1].name;
          if (answer === food[i].rightAnswer) {
            score = score + 1;
            document.getElementById("score").innerHTML = score;
            document.getElementById("message").innerHTML = "Right answer";
            nextQuestion();
          } else {
            score = score - 0.5;
            document.getElementById("score").innerHTML = score;
            document.getElementById("message").innerHTML = "wrong answer, please try again";
          }
        }
      }
    }
    
    function nextQuestion() {
      let qNum = document.getElementById("questionNumber").innerHTML;
      let num = ++qNum;
      if (num === 10) {
        num = 0;
      }
      document.getElementById("questionNumber").innerHTML = num;
      document.getElementById("score").innerHTML = score;
      document.getElementById("word").innerHTML = food[num].word;
      document.getElementById("image").innerHTML = "";
      let imgSrc = food[num].img;
      let img = document.createElement("img");
      img.src = food[num].img;
      img.width = '500';
      img.height = '300';
      document.getElementById("image").appendChild(img);
      document.getElementById("options").innerHTML = "";
      document.getElementById("options").innerHTML =
        "<button class='btn' id='1' onclick='checkAnswer(food[" + num + "].ID,this)'></button> " +
        "<button class='btn' id='2' onclick='checkAnswer(food[" + num + "].ID,this)'></button> " +
        "<button class='btn' id='3' onclick='checkAnswer(food[" + num + "].ID,this)'></button>";
      document.getElementById("options").getElementsByTagName('button')[0].innerHTML = food[num].options[0].name;
      document.getElementById("options").getElementsByTagName('button')[1].innerHTML = food[num].options[1].name;
      document.getElementById("options").getElementsByTagName('button')[2].innerHTML = food[num].options[2].name;
      debugger;
    }
    
    
    function prevQuestion() {
      let qNum = document.getElementById("questionNumber").innerHTML;
      let num = --qNum;
      if (num === -1) {
        num = 10;
      }
      document.getElementById("questionNumber").innerHTML = num;
      document.getElementById("score").innerHTML = score;
      document.getElementById("word").innerHTML = food[num].word;
      document.getElementById("image").innerHTML = "";
      let imgSrc = food[num].img;
      let img = document.createElement("img");
      img.src = food[num].img;
      img.width = '500';
      img.height = '300';
      document.getElementById("image").appendChild(img);
      document.getElementById("options").innerHTML = "";
      document.getElementById("options").innerHTML =
        `<button class='btn' id='1' onclick='checkAnswer(food[` + num + `].ID,this)'></button> <button class='btn' id='2' onclick='checkAnswer(food[` + num + `].ID,this)'></button> <button class='btn' id='3' onclick='checkAnswer(food[` + num + `].ID,this)'></button>`;
      document.getElementById("options").getElementsByTagName('button')[0].innerHTML = food[num].options[0].name;
      document.getElementById("options").getElementsByTagName('button')[1].innerHTML = food[num].options[1].name;
      document.getElementById("options").getElementsByTagName('button')[2].innerHTML = food[num].options[2].name;
    }
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Game</title>
    </head>
    
    <body id="gameBody" onload="InitGame()">
    
      <h1>Welcome to the game</h1>
      <h3 class="header">Your score</h3>
      <h3 class="text" id="score"></h3>
      <h5 class="header">Choose the right answer</h5>
      <p class="header">The question number</p>
      <p class="text" id="questionNumber"></p>
      <p class="header">The word you need to translate</p>
      <p id="word"></p>
      <div id="image">
    
      </div>
      <div id="options">
    
      </div>
      <p id="message"></p>
      <button class="myChoise" onclick="prevQuestion()">Previous</button>
      <button class="myChoise" onclick="nextQuestion()">Next</button>
    
    </body>
    
    </html>

    【讨论】:

      猜你喜欢
      • 2021-07-17
      • 1970-01-01
      • 2017-05-22
      • 2017-05-10
      • 1970-01-01
      • 2022-10-30
      • 2019-10-27
      • 1970-01-01
      相关资源
      最近更新 更多