【问题标题】:JavaScript Quiz App Working Correctly But With An Uncaught Type ErrorJavaScript 测验应用程序工作正常但有未捕获的类型错误
【发布时间】:2020-10-18 06:22:19
【问题描述】:

我的代码运行良好 但我仍然收到错误“Quiz.html:179 Uncaught TypeError: Cannot read property 'answer' of undefined”

我不知道为什么 我已经尝试了所有可能的方法。 我对此很感兴趣。 请帮我! ` 让开始 = document.getElementById('start'); 让 buttonY = document.createElement('button'); buttonY.innerText = '是'; buttonY.className = '选项'; 让 buttonN = document.createElement('button'); buttonN.innerText = '否'; buttonN.className = '选项'; 让回应; 让分数 = 0; 让我 = 0; 让 displayQuestions = document.getElementById('question'); 让问题答案 = [ { 问题:'HTML 是一种编程语言?', 回答:'不', }, { 问题:'JavaScript 是一种脚本语言?', 回答:'是的', }, ];

  start.addEventListener('click', () => {
    next();
  });

  function next() {
    start.style.display = 'none';

    if (i < questionAnswer.length) {
      displayQuestions.style.display = 'block';
      displayQuestions.innerHTML = questionAnswer[i].question;

      displayQuestions.appendChild(buttonY);
      displayQuestions.appendChild(buttonN);

      buttonY.addEventListener('click', () => {
        response = buttonY.innerText;

        if (response == questionAnswer[i].answer) {
          score++;
          console.log(response);
        } else {
          alert('Wrong Answer');
        }
        response = '';
        i++;
        next();
      });
      buttonN.addEventListener('click', () => {
        response = buttonN.innerText;
        if (response == questionAnswer[i].answer) {
          score++;
          console.log(response);
        } else {
          alert('Wrong Answer');
        }
        response = '';
        i++;
        next();
      });
    } else {
      check();
    }
  }

  function check() {
    displayQuestions.innerText = `Score is ${score}`;
  }
</script>`

【问题讨论】:

    标签: javascript


    【解决方案1】:

    问题在于您在 next 函数中定义了按钮 eventListener。我给你发了little sandbox

    【讨论】:

      猜你喜欢
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-03
      • 2019-02-20
      相关资源
      最近更新 更多