如何通过JavaScript单击按钮来启动一个测验?

huangapple go评论58阅读模式
英文:

How can I initiate a quiz by clicking on a button in JavaScript?

问题

我已经构建了一个问答应用程序。我希望用户能够点击播放按钮,然后在用户完成第一轮后重新从第一个问题开始。目前,如果用户开始回答问题,在最后一个问题之后,会出现播放按钮供用户点击并继续播放。当前的问题是,当点击播放按钮时,会出现来自第40行的错误,提示无法读取未定义。

var questionElement = document.getElementById('questions');
var answerElement = document.getElementById('answers');
var scoreBoard = document.querySelector('#score-board');
const playBtn = document.querySelector('#play-btn');
const playScore = document.querySelector('#play-score');
const state = {
    currentQuestionIndex: 0,
    score: 0
};

var questions = [
    { question: "1. JavaScript 是一种....... 语言吗?",
      answers: ["面向对象", "基于对象", "过程式", "以上都不是"],
      correct: 1
    },
    { question: "2. 以下哪个关键字用于在 JavaScript 中定义变量?",
      answers: ["var", "let", "A 和 B", "以上都不是"],
      correct: 2
    },
    {
      question: "3. 以下哪种方法用于使用 JavaScript 操作 HTML 元素?",
      answers: ["getElementById", "getElementByClassName", "A 和 B", "以上都不是"],
      correct: 2
    }
];

function showQuestion(questionIndex) {
    const question = questions[questionIndex];
    const qDiv = document.createElement('div');
    const p = document.createElement('p');

    questionElement.innerHTML = "";
    answerElement.innerHTML = "";

    p.textContent = question.question;
    qDiv.appendChild(p);
    questionElement.appendChild(qDiv);

    question.answers.forEach((answers, answerIndex) => {
        const $input = document.createElement('input');
        const $label = document.createElement('label');
        $label.appendChild($input);

        $label.appendChild(document.createTextNode(answers));
        $input.name = `question${questionIndex}`;
        $input.type = 'radio';
        $input.value = answerIndex;
        answerElement.append($label);
    });
}

var nBtn = document.querySelector('.nbtn');
nBtn.addEventListener('click', nextQuestion);

const $answers = document.getElementById("answers");
$answers.addEventListener("change", (event) => {
    const currentQuestion = questions[state.currentQuestionIndex];
    const selectedAnswerIndex = Number(event.target.value);
    const correctAnswerIndex = currentQuestion.correct;
    const isCorrect = selectedAnswerIndex === correctAnswerIndex;
    state.score += isCorrect ? 1 : 0;
});
showQuestion(0);

function nextQuestion() {
    state.currentQuestionIndex += 1;
    if (state.currentQuestionIndex === questions.length) {
        removeLastQuestion();
        hidePlayBtn();
        showScores();
        showPlayBtn();
    } else {
        showQuestion(state.currentQuestionIndex)
    }
}

function showScores() {
    if (state.currentQuestionIndex === questions.length) {
        scoreBoard.innerHTML = `${state.score}/${questions.length}`
    }
}

function removeLastQuestion() {
    if (state.currentQuestionIndex > questions.length - 1) {
        questionElement.innerHTML = "";
        answerElement.innerHTML = "";
    }
}

function scorePage() {
    if (state.currentQuestionIndex > questions.length - 1) {
        window.location.href = 'index23.html';
    }
}

const score = document.querySelector('#play-score');
score.addEventListener('click', () => {
    scoreBoard.innerText = `${state.score}/${questions.length}`;
});

const hidePlayBtn = function() {
    nBtn.style display = 'none';
    playScore.style.display = 'none';
}

const init = function() {
    // showQuestion(0);
}

const showPlayBtn = function() {
    playBtn.style.display = 'block';
}

window.onload = function() {
    showQuestion(0);
    playBtn.style.display = 'none';
    playScore.style.display = 'none';
}

playBtn.addEventListener('click', () => {
    showQuestion(state.currentQuestionIndex);
    // nextQuestion();
    // showQuestion(state.currentQuestionIndex)
    // init();
    // nBtn.style.display = 'block';
});

请注意,我已经将您的代码翻译成中文,如有任何问题,请随时提出。

英文:

I've build a quiz app. I want the user to be able to click a play button and the quiz start again from question one after the user has finished the first round. right now, if the user starts answering the question, after the last question the play button appears for the user to click and continue playing. the problem right now is when the click on play there is an error from line 40 saying cannot read undefined.

var questionElement = document.getElementById('questions');
var answerElement = document.getElementById('answers');
var scoreBoard = document.querySelector('#score-board');
const playBtn = document.querySelector('#play-btn');
const playScore = document.querySelector('#play-score');
const state = {
currentQuestionIndex: 0,
score: 0
};
var questions = [
{ question: " 1. javaScript is an....... language?",
answers: [ "object-oriented", "object-based", "procedural", "none of the above"],
correct: 1
},
{ question: " 2.which of the following keywords is used a define variable in javaScript",
answers: [ "var", "let", "both A and B", "none of the above"],
correct: 2
}, 
{
question: "3. which of the following methods is used to HTML elements using javaScript",
answers: ["getElementsById", "getElementByClassName", "both A and B", "none of the above"] ,
correct: 2
}
];
function showQuestion(questionIndex){
const question = questions[questionIndex];
const qDiv = document.createElement('div');
const p = document.createElement('p');
questionElement.innerHTML = "";
answerElement.innerHTML = "";
p.textContent = question.question;
qDiv.appendChild(p);
questionElement.appendChild(qDiv);
question.answers.forEach((answers, answerIndex) =>{
const $input = document.createElement('input');
const $label = document.createElement('label');
$label.appendChild($input);
$label.appendChild(document.createTextNode(answers));
$input.name = `question${questionIndex}`;
$input.type = 'radio';
$input.value = answerIndex;
answerElement.append($label);
});
};
var nBtn = document.querySelector('.nbtn');
nBtn.addEventListener('click', nextQuestion);
const $answers = document.getElementById("answers");
$answers.addEventListener("change", (event) => {
const currentQuestion = questions[state.currentQuestionIndex];
const selectedAnswerIndex = Number(event.target.value);
const correctAnswerIndex = currentQuestion.correct;
const isCorrect = selectedAnswerIndex === correctAnswerIndex;
state.score += isCorrect ? 1 : 0;
});
showQuestion(0);
function nextQuestion() {
state.currentQuestionIndex += 1;
if (state.currentQuestionIndex === questions.length) {
removeLastQuestion();
hidePlayBtn();
//scorePage();
showScores();
showPlayBtn();
} else{
showQuestion(state.currentQuestionIndex)
}	
};
function showScores() {
if (state.currentQuestionIndex === questions.length) {
scoreBoard.innerHTML = `${state.score}/${questions.length}`
}	
}
function removeLastQuestion(){
if (state.currentQuestionIndex > questions.length - 1) {
questionElement.innerHTML = "";
answerElement.innerHTML = "";
}	
}
function scorePage() {
if (state.currentQuestionIndex > questions.length -1) {
window.location.href = 'index23.html';
}
}
const score = document.querySelector('#play-score');
score.addEventListener('click', ()=>{
scoreBoard.innerText = `${state.score}/${questions.length}`;
});
const hidePlayBtn = function() {
nBtn.style.display = 'none';
playScore.style.display = 'none';
}
const init = function() {
// showQuestion(0);
}
const showPlayBtn = function() {
playBtn.style.display = 'block';
}
window.onload = function() {
showQuestion(0);
playBtn.style.display = 'none';
playScore.style.display = 'none';
}
playBtn.addEventListener('click', ()=>{
showQuestion(state.currentQuestionIndex);
// nextQuestion();
// showQuestion(state.currentQuestionIndex)
// init();
// nBtn.style.display = 'block';
});

答案1

得分: 1

你应该将 state 设置为一个变量,而不是一个常量

然后在 showPlayBtn 函数中,将 state.currentQuestionIndex 重置为 0

希望这有所帮助

英文:

You should have set the state as a variable, not a const

And then in the showPlayBtn function, reset the state.currentQuestionIndex to 0

I hope this helps

huangapple
  • 本文由 发表于 2023年2月27日 08:17:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75575841.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定