如何让 javascript 重新确认正在单击测验应用程序的正确答案?

时间:2021-03-01 16:34:56

标签: javascript visual-studio function if-statement event-listener

我正在尝试使用 javascript 制作一个测验应用程序,但我在使代码识别出正确答案被点击时遇到了一些问题。它只是说有一个错误,并且第 45 行没有定义“正确”的语法。我对编码很陌生,我仍然不完全知道我在做什么。事实上,这是我第一次使用stackoverflow。这是我的 javascript:

var quizButton = document.querySelector('#start');
var displayedQuestion = document.querySelector('.quiz-container');
var hideStartScreen = document.querySelector('#start-up-screen');
var questionElement = document.querySelector('.quiz-question');
var answerElement = document.querySelector('.answer-button');
var highScore = [];
var quizQuestions = [{question: "A very useful tool to help with debugging and printing content to the debugger is the: ",
choices: [{text: "Console Log", correct: true}, {text: "Terminal", correct: false}, {text: "Ice Cream", correct: false}, {text: "Javascript", correct: false}], 
}];
let shuffleQuestions, currentQuestionIndex;


function startQuiz() {
    console.log("Quiz Started!");
    hideStartScreen.classList.add('hide');
    displayedQuestion.classList.remove('hide');
    shuffleQuestions = quizQuestions.sort(() => Math.random () - .5);
    currentQuestionIndex = 0;
    nextQuestion();
};

function nextQuestion() {
    console.log("Next Question");
    generateQuestion (shuffleQuestions[currentQuestionIndex]);
    
};

function generateQuestion (question) {
    console.log("Generating Question");
    questionElement.innerHTML = question.question;
    question.choices.forEach(answer => {
        const button = document.createElement('button'); 
        button.innerText = answer.text;
        button.classList.add('btn');
        if (answer.correct) {
            button.dataset.correct = answer.correct
        };
        button.addEventListener('click', selectAnswer);
        answerElement.appendChild(button);
    })
}

function selectAnswer () {
    console.log('cicked!');
    if (quizQuestions.choices.correct == true) {
        console.log('Correct!');
    } else {
        console.log('Wrong!');
    }
}

//Start the quiz by pressing the start button
quizButton.addEventListener("click",  startQuiz)

先谢谢你。我希望我说得够清楚了。

1 个答案:

答案 0 :(得分:0)

那是因为您试图在下面的行中的问题选择和选择选择中使用对象表示法访问数组:

    if (quizQuestions.choices.correct == true) {

如果你想获得第一个问题的第一选择,试试这个:

quizQuestions[0].choices[0].correct

“quizQuestions”变量是一个数组,而“choices”是一个数组。如果你不知道数组是什么,谷歌一下,然后你就会明白。

希望能帮到你

相关问题