gpt4 book ai didi

javascript - 无法让我的测验应用程序工作

转载 作者:行者123 更新时间:2023-11-27 23:50:05 25 4
gpt4 key购买 nike

我正在 http://javascriptissexy.com/how-to-learn-javascript-properly/ 上做“正确学习 JavaScript”类(class).

我花了很长时间,但我终于想出了如何进入下一个问题,但选择没有改变。

但是,当我对“questionIndex”进行硬编码时,问题和选择工作正常。

无论如何,这是我的代码(我知道它有点乱,我是初学者):

http://jsfiddle.net/utfwae8d/1/

HTML:

<div id="container">
<div id="quiz"></div>
<div id="choices"></div>
<input type="button" value="Next">
</div>

JavaScript:

var allQuestions = [{
question: "Who is the best in the world?",
choices: ["CM Punk", "John Cena", "Daniel Bryan", "Roman Reigns"],
correctAnswer: 0
},

{
question: "Who is the current WWE World Champion?",
choices: ["John Cena", "Brock Lesnar", "Triple H"],
correctAnswer: 1
},

{
question: "Where is Toronto located?",
choices: ["Ontario", "California", "Georgia", "Texas"],
correctAnswer: 0
},

{
question: "What is the largest California city?",
choices: ["Los Angeles", "San Fransico", "San Deigo", "Anahiem"],
correctAnswer: 0
}];

var quiz = document.getElementById('quiz');
var choicesContainer = document.getElementById('choices');
var nextButton = document.querySelector('[type=button]');

var correctAnswers = 0;
var questionIndex = 0;


function showQuiz() {
var currentQuestion = allQuestions[questionIndex].question;
quiz.textContent = currentQuestion;

var choicesNum = allQuestions[questionIndex].choices.length;
var correctAnswer = allQuestions[questionIndex].correctAnswer;

var choices;

for (var i = 0; i < choicesNum; i++) {
choices = allQuestions[questionIndex].choices[i];
choicesHTML = "<input type='radio' name='choice'>" + choices + "</br>";

choicesContainer.innerHTML += choicesHTML;
}

nextButton.addEventListener('click', function () {
questionIndex++;
quiz.textContent = allQuestions[questionIndex].question;
});


}

showQuiz();

最佳答案

按钮的点击处理程序不会更新答案,它只会更新问题。

我将代码分成两个函数:一个显示测验,一个显示答案。

var quiz = document.getElementById('quiz');
var choicesContainer = document.getElementById('choices');
var nextButton = document.querySelector('[type=button]');

var questionIndex = 0;

function showAnswers() {
choicesContainer.innerHTML = "";
var choicesNum = allQuestions[questionIndex].choices.length;
for (var i = 0; i < choicesNum; i++) {
var choice = allQuestions[questionIndex].choices[i];
choicesHTML = "<input type='radio' name='choice'>" + choice + "</br>";
choicesContainer.innerHTML += choicesHTML;
}
}

function showQuiz() {
var currentQuestion = allQuestions[questionIndex].question;
quiz.textContent = currentQuestion;
}

showQuiz();
showAnswers();

nextButton.addEventListener('click', function () {
questionIndex++;
showQuiz();
showAnswers();
});

关于javascript - 无法让我的测验应用程序工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27832311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com