Я работаю с викториной, и для этого я создаю несколько функций.
$(document).ready(function () {
start(questionNumber);
$(".submit-answer").on("click", function (event) {
var userAnswer = parseInt($(this).attr("id"));
answerCheck(userAnswer);
setTimeout(function () {
$(".submit-answer").remove();
$(".submit-answer").removeClass("correctStyle incorrectStyle");
start(questionNumber);
}, 1500)
questionNumber++;
});
});
var questionNumber = 0,
totalCorrect = 0,
optionFinal = 0;
var allQuestions = [
{
question: 'Test question',
choices: ["Answer 1", "Answer 2", "Answer 3", "Answer 4", "Answer 5", "Answer 6"],
answer: 0
}, {
question: 'Test question',
choices: ["Answer 1", "Answer 2", "Answer 3", "Answer 4"],
answer: 0
},
{
question: 'Test question',
choices: ["Answer 1", "Answer 2", "Answer 3", "Answer 4", "Answer 5"],
answer: 0
},
{
question: 'Test question',
choices: ["Answer 1", "Answer 2", "Answer 3", "Answer 4", "Answer 5", "Answer 6"],
answer: 0
}
];
// continue with next question or end
var start = function (questionNumber) {
$('h2').hide().fadeIn(400);
if (questionNumber !== allQuestions.length) {
question(questionNumber);
} else {
end();
}
};
// show question and possible answers
function question(questionNum) {
$("h2").text(allQuestions[questionNum].question);
$.each(allQuestions[questionNum].choices, function (i, answers) {
var buttons = `<button class="submit-answer" id="${i}"></button>`;
$(".buttons-creation").append(buttons);
$("#" + i).html(answers);
});
};
function end() {
$(".buttons-creation").hide();
$("h2").text("You scored " + totalCorrect + " out of " + allQuestions.length);
$("#try-again-container").show();
restart();
};
function restart() {
$("#try-again").click(function () {
questionNumber = 0,
totalCorrect = 0,
optionFinal = 0;
start(questionNumber);
$("#try-again-container").hide();
$(".buttons-creation").show();
});
}
function answerCheck(userAnswer) {
var correctAnswer = allQuestions[questionNumber].answer;
if (userAnswer === correctAnswer) {
$("#" + userAnswer).addClass("correctStyle");
totalCorrect++;
} else {
$("#" + userAnswer).addClass("incorrectStyle");
}
};
HTML:
<h2></h2>
<div id="try-again-container" style="display:none;"><button id="try-again">Try Again</button></div>
<div class="buttons-creation">
</div>
Итак, проблема в том, что я хочу сгенерировать кнопку для ответов динамически, для этого я использую для каждого. Но если я go к следующему вопросу, он не удаляет previus, для этого я пытаюсь использовать:
$ (". Submit-answer"). Remove ();
Это работает, но только один раз, после того как ответ на вопрос остановлен.