Проблема, связывающая изображения с динамически созданными jquery элементами - PullRequest
0 голосов
/ 28 января 2020

Итак, я очень новичок, поэтому прошу прощения, если это глупый вопрос. Я разработал викторину викторины для моего обучения кодам, которые я беру. Я хочу отобразить изображение на экране подтверждения, которое показывает, был ли пользователь прав или нет. Я думаю, что код правильный-я sh? Я не уверен, что не работает. Я оставил основной вопрос и ответ на объект в космосе. Извините, если я не отформатировал это в идеале? Я все еще пытаюсь понять, как все здесь работает.

Вот мой код для справки:

    //array to help me iterate and insert images
    var imgArray = ["question1", "question2", "question3", "question4", "question5", "question6", "question7", "question8", "question9", "question10", "question11", "question12", "question13"];
    var currentQuestion = 0;

    var win = 0;
    var lose = 0;
    var unanswered = 0;
    var time = 30;

    //set up divs to contain our info
    var rightDiv = $("<div class='rightAns'></div>");
    var timerDiv = $("<div class='countdown'><h3></h3></div>");
    var questionDiv = $("<div class='question'><h1></h1></div><br>");
    var answerDiv = $("<div class='answers'></div>");

    //object keys to return questions in order
    var keys = Object.keys(questions);
    var key = keys[n];
    var n = 0;

    //function to setup and restart game
    function reset() {
        $("#start-button").hide("slow");
        $("#start-here").hide("slow");
        win = 0;
        lose = 0;
        unanswered = 0;
        n = 0;
        key = keys[n];
        currentQuestion = 0;
        $("#question-block").empty();

        var reset = function () {
            time = 30;
            $(".rightAns").empty();
            $(".rightAns").remove();
            // $("#image").empty();
            $("#time-remaining").append(timerDiv);
            $(".countdown h3").html("Time Remaining: " + time);
            $("#question-block").append(questionDiv);
            $("#question-block").append(answerDiv);
        }
        reset();

        //function to show questions
        function showQuestion() {
            $(".question h1").html(questions[key].question);

            for (var i = 0; i < questions[key].answers.length; i++) {
                $(".answers").append("<button class='answer btn btn-danger btn-lg m-1'>" + questions[key].answers[i] + "</button>");
            }

            $(".answers button").on("click", function () {
                var selected = $(this).text();
                //if then to check question correctness
                if (selected === questions[key].correct) {
                    clearInterval(counter);
                    $(timerDiv).remove();
                    $(questionDiv).remove();
                    $(".answers button").remove();
                    $(answerDiv).remove();
                    $("#correct-answer").append(rightDiv);
                    $(".rightAns").text("That's Correct!!");
                    $("#image").html('<img src = ".assets/images/' + imgArray[currentQuestion] + '" width = "400px">');
                    win++;
                    currentQuestion++;
                } else {
                    clearInterval(counter);
                    $(timerDiv).remove();
                    $(questionDiv).remove();
                    $(".answers button").remove();
                    $(answerDiv).remove();
                    $("#correct-answer").append(rightDiv);
                    $(".rightAns").text("Nope! The correct answer was: " + questions[key].correct);
                    $("#image").html('<img src = ".assets/images/' + imgArray[currentQuestion] + '" width = "400px">');
                    lose++;
                    currentQuestion++;
                }
                n++;
                key = keys[n];

                //checking to see if there are more questions left
                if (checkForLast()) {
                    finalScore();
                } else {
                    setTimeout(countReset, 3 * 1000);
                    setTimeout(reset, 3 * 1000);
                    setTimeout(showQuestion, 3 * 1000);
                }
            });
        }

        showQuestion();

        var counter = setInterval(count, 1000);

        //show time remaining for each question
        function count() {
            time--;
            $(".countdown h3").html("Time Remaining: " + time);

            if (time < 1) {
                clearInterval(counter);
                $(timerDiv).remove();
                $(questionDiv).remove();
                $(".answers button").remove();
                $("#correct-answer").append(rightDiv);
                $(".rightAns").html("You took too long! The correct answer was: " + questions[key].correct);
                unanswered++;
                n++;
                key = keys[n];

                if (checkForLast()) {
                    finalScore();
                } else {
                    setTimeout(countReset, 3 * 1000);
                    setTimeout(reset, 3 * 1000);
                    setTimeout(showQuestion, 3 * 1000);
                }
            }
        }

        function checkForLast() {
            if (key === undefined) {
                return true;
            }
            return false;
        }

        //timer for the message after you choose your answer
        function countReset() {
            counter = setInterval(count, 1000);
        }

        //showthe final score screen
        function finalScore() {
            $(".rightAns").remove();
            $("#image").empty();
            $("#question-block").prepend("<h2>Unanswered: " + unanswered + "</h2>");
            $("#question-block").prepend("<h2>Incorrect: " + lose + "</h2>");
            $("#question-block").prepend("<h2>Correct: " + win + "</h2>");
            $("#start-button").show();
            $("#start-here").show();
        }
    };

    //function to start game on button click
    $(document).on("click", "#start-button", reset);
});

1 Ответ

0 голосов
/ 28 января 2020

Немного повозившись, я опустил "." в начале вызова и добавил .jpg в раздел после imgArray [currentQuestion]. Это решило это. Спасибо за предложения.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...