如何从div测验按钮jquery中删除元素

问题描述 投票:0回答:1

我参加测验,为此我创建了一些功能。

$(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>

所以,问题是:我想动态生成用于答案的按钮,为此我使用了每个按钮。但是,如果我转到下一个问题,它并不能消除先前的问题,为此,我尝试使用:

$(“。submit-answer”)。remove();

这是可行的,但是在问题脚本的答案停止后只有一次。

javascript jquery
1个回答
0
投票
您从DOM中删除了所有带有“提交-回答”类的按钮。之后,您必须动态添加这些按钮。像那样:enter image description here
© www.soinside.com 2019 - 2024. All rights reserved.