JavaScript测验应用程序正常运行,但出现类型错误

时间:2020-10-18 06:22:19

标签: javascript

我的代码运行正常 但仍然出现错误“ Quiz.html:179未捕获的TypeError:无法读取未定义的属性'answer'”

我不知道为什么 我尝试了所有可能的方式。 我对此真的很感兴趣。 请帮我! ` 让开始= 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'); 让questionAnswer = [ { 问题:“ 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>`

1 个答案:

答案 0 :(得分:0)

问题是您在下一个函数中定义了按钮eventListener。我给你做了little sandbox