简体   繁体   English

如何在测验中显示正确答案?

[英]How can I show the correct answer in my quiz?

I would like to be able to show the user what the correct answer to the question is if the one that they selected was incorrect. 我希望能够向用户显示该问题的正确答案是,如果他们选择的答案不正确。 I would like to keep it simple, but here is what I am thinking. 我想保持简单,但这就是我的想法。 Once the user submits their answer and if it is incorrect, before moving onto the next question I would like for the incorrect answer to be highlighted in red, and the correct answer to be highlighted in green. 一旦用户提交了答案(如果答案不正确),在继续下一个问题之前,我希望将不正确的答案用红色突出显示,并将正确的答案用绿色突出显示。

I already have coded whether or not the answer is correct or incorrect, but I haven't been able to figure out how to be able to show the correct answer if an incorrect one is chosen. 我已经编码了答案是正确还是不正确,但是如果选择了错误答案,我还无法弄清楚如何显示正确答案。

 let score = 0; let currentQuestion = 0; let questions = [{ title: "At what age was Harry Potter when he received his Hogwarts letter?", answers: ['7', '10', '11', '13'], correct: 1 }, { title: "Which is not a Hogwarts house?", answers: ['Dunder Mifflin', 'Ravenclaw', 'Slytherin', 'Gryffindor'], correct: 0 }, { title: "Who teaches Transfiguration at Hogwarts?", answers: ['Rubeus Hagrid', 'Albus Dumbledore', 'Severus Snape', 'Minerva McGonnagle'], correct: 3 }, { title: "Where is Hogwarts School for Witchcraft and Wizardry located?", answers: ['France', 'USA', 'UK', 'New Zealand'], correct: 2 }, { title: "What form does Harry Potter's patronus charm take?", answers: ['Stag', 'Eagle', 'Bear', 'Dragon'], correct: 0 }, { title: "What type of animal is Harry's pet?", answers: ['Dog', 'Owl', 'Cat', 'Snake'], correct: 1 }, { title: "Who is not a member of the Order of the Phoenix?", answers: ['Remus Lupin', 'Siruis Black', 'Lucious Malfoy', 'Severus Snape'], correct: 2 }, { title: "What is not a piece of the Deathly Hallows?", answers: ['Elder Wand', 'Cloak of Invisibility', 'Resurrection Stone', 'Sword of Gryffindor'], correct: 3 }, { title: "In which house is Harry sorted into after arriving at Hogwarts?", answers: ['Slytherin', 'Ravenclaw', 'Gryffindor', 'Hufflepuff'], correct: 2 }, { title: "What prevented Voldemort from being able to kill Harry Potter when he was a baby?", answers: ['Love', 'Anger', 'Friendship', 'Joy'], correct: 0 }, ]; $(document).ready(function() { $('.start a').click(function(e) { e.preventDefault(); $('.start').hide(); $('.quiz').show(); showQuestion(); }); $('.quiz ul').on('click', 'li', function() { $('.selected').removeClass('selected'); $(this).addClass('selected'); }); $('.quiz a').click(function(e) { e.preventDefault(); if ($('li.selected').length) { let guess = parseInt($('li.selected').attr('id')); checkAnswer(guess); } else { alert('Please select an answer'); } }); $('.summary a').click(function(e) { e.preventDefault(); restartQuiz(); }); }); function showQuestion() { let question = questions[currentQuestion]; $('.quiz h2').text(question.title); $('.quiz ul').html(''); for (var i = 0; i < question.answers.length; i++) { $('.quiz ul').append(`<li id="${i}">${question.answers[i]}</li>`); } showProgress(); } function checkAnswer(guess) { let question = questions[currentQuestion]; if (question.correct === guess) { score++; showIsCorrect(true); } else { showIsCorrect(false); } currentQuestion++; if (currentQuestion >= questions.length) { showSummary(); } else { showQuestion(); } } function showSummary() { $('.quiz').hide(); $('.summary').show(); $('.summary p').text("Thank you for taking the quiz! Here's how you scored. You answered " + score + " out of " + questions.length + " correctly! Care to try again?") } function restartQuiz() { $('.summary').hide(); $('.quiz').show(); score = 0; currentQuestion = 0; showQuestion(); } function showProgress() { $('#currentQuestion').html(currentQuestion + " out of " + questions.length); } function showIsCorrect(isCorrect) { var result = "Wrong"; if (isCorrect) { result = "Correct"; } $('#isCorrect').html(result); } 
 * { padding: 0; margin: 0; box-sizing: border-box; text-decoration: none; text-align: center; background-color: #837F73; } h1 { font-family: 'Poor Story', cursive; background-color: #950002; padding: 60px; color: #FFAB0D; text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black; } h2 { font-family: 'Poor Story', cursive; font-size: 30px; padding: 60px; background-color: #950002; color: #FFAB0D; text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black; } p { font-family: 'Poor Story', cursive; background-color: #FFAB0D; font-size: 20px; font-weight: bold; } a { border: 1px solid #222F5B; padding: 10px; background-color: #222F5B; color: silver; border-radius: 5px; margin-top: 50px; display: inline-block; } a:hover { border: 1px solid #000000; background-color: #000000; color: #FCBF2B; } .quiz li { cursor: pointer; border: 1px solid; display: inline-block; width: 200px; margin: 10px; font-family: 'Poor Story', cursive; font-size: 26px; } #currentQuestion { color: #000000; font-size: 18px; font-family: 'Poor Story', cursive; margin-top: 10px; } #isCorrect { color: white; font-family: 'Poor Story', cursive; font-weight: bold; font-size: 18px; } .quiz, .summary { display: none; } .quiz ul { margin-top: 20px; list-style: none; padding: 0; } .selected { background-color: #398C3F; } 
 <!DOCTYPE html> <html> <head> <link href="https://fonts.googleapis.com/css?family=Poor+Story" rel="stylesheet"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <div class="start"> <h1>How Well Do You Know Harry Potter?</h1> <a href="#">Start Quiz</a> </div> <div class="quiz"> <h2>Question Title</h2> <ul> <li>Choice</li> <li>Choice</li> <li>Choice</li> <li>Choice</li> </ul> <a href="#">Submit Answer</a> <div id="currentQuestion"></div> <div id="isCorrect"></div> </div> <div class="summary"> <h2>Results</h2> <p>Thank you for taking the quiz! Here's how you scored. You answered x out of y correctly! Care to try again?</p> <a href="#">Retake Quiz</a> </div> <script src="https://code.jquery.com/jquery-3.1.0.js"></script> </body> </html> 

Just a quick heads up that under this implementation, anybody who inspects the your javascript file will be able to see the answers to your quiz, even if it is minified/uglified! 快速了解在此实现下,即使您的JavaScript文件已缩小/已被丑化,任何检查您的javascript文件的人都可以看到您的测验答案! I doubt that anyone taking this Harry Potter quiz is going to reverse engineer it (hopefully), but you never know! 我怀疑有人参加这个“哈利·波特”测验是否会对它进行反向工程(希望如此),但您永远不知道! If you wanted to make the quiz more secure, you create a web service and then validate answers via HTTP requests . 如果您想提高测验的安全性,请创建一个Web服务,然后通过HTTP request验证答案。

Anyways, for learning purposes, you can modify your code to display the answer by changing the following. 无论如何,出于学习目的,您可以通过更改以下内容来修改代码以显示答案。 As for the coloring, see addClass in the jQuery documentation and try defining some of your own classes for right and wrong answers. 至于颜色,请参阅jQuery文档中的addClass并尝试定义一些自己的类,以获取对与错的答案。 You can also check out this mdn documentation for some basics on web architecture. 您也可以查看此mdn文档 ,了解有关Web体系结构的一些基础知识。

Also, welcome to Stack Overflow and good luck! 另外,欢迎来到Stack Overflow,祝您好运!

 let score = 0; let currentQuestion = 0; let questions = [{ title: "At what age was Harry Potter when he received his Hogwarts letter?", answers: ['7', '10', '11', '13'], correct: 1 }, { title: "Which is not a Hogwarts house?", answers: ['Dunder Mifflin', 'Ravenclaw', 'Slytherin', 'Gryffindor'], correct: 0 }, { title: "Who teaches Transfiguration at Hogwarts?", answers: ['Rubeus Hagrid', 'Albus Dumbledore', 'Severus Snape', 'Minerva McGonnagle'], correct: 3 }, { title: "Where is Hogwarts School for Witchcraft and Wizardry located?", answers: ['France', 'USA', 'UK', 'New Zealand'], correct: 2 }, { title: "What form does Harry Potter's patronus charm take?", answers: ['Stag', 'Eagle', 'Bear', 'Dragon'], correct: 0 }, { title: "What type of animal is Harry's pet?", answers: ['Dog', 'Owl', 'Cat', 'Snake'], correct: 1 }, { title: "Who is not a member of the Order of the Phoenix?", answers: ['Remus Lupin', 'Siruis Black', 'Lucious Malfoy', 'Severus Snape'], correct: 2 }, { title: "What is not a piece of the Deathly Hallows?", answers: ['Elder Wand', 'Cloak of Invisibility', 'Resurrection Stone', 'Sword of Gryffindor'], correct: 3 }, { title: "In which house is Harry sorted into after arriving at Hogwarts?", answers: ['Slytherin', 'Ravenclaw', 'Gryffindor', 'Hufflepuff'], correct: 2 }, { title: "What prevented Voldemort from being able to kill Harry Potter when he was a baby?", answers: ['Love', 'Anger', 'Friendship', 'Joy'], correct: 0 }, ]; $(document).ready(function() { $('.start a').click(function(e) { e.preventDefault(); $('.start').hide(); $('.quiz').show(); showQuestion(); }); $('.quiz ul').on('click', 'li', function() { $('.selected').removeClass('selected'); $(this).addClass('selected'); }); $('.quiz a').click(function(e) { e.preventDefault(); if ($('li.selected').length) { let guess = parseInt($('li.selected').attr('id')); checkAnswer(guess); } else { alert('Please select an answer'); } }); $('.summary a').click(function(e) { e.preventDefault(); restartQuiz(); }); }); function showQuestion() { let question = questions[currentQuestion]; $('.quiz h2').text(question.title); $('.quiz ul').html(''); for (var i = 0; i < question.answers.length; i++) { $('.quiz ul').append(`<li id="${i}">${question.answers[i]}</li>`); } showProgress(); } function checkAnswer(guess) { let question = questions[currentQuestion]; if (question.correct === guess) { score++; showIsCorrect(true, questions[question.correct]); } else { showIsCorrect(false, questions[question.correct]); } currentQuestion++; if (currentQuestion >= questions.length) { showSummary(); } else { showQuestion(); } } function showSummary() { $('.quiz').hide(); $('.summary').show(); $('.summary p').text("Thank you for taking the quiz! Here's how you scored. You answered " + score + " out of " + questions.length + " correctly! Care to try again?") } function restartQuiz() { $('.summary').hide(); $('.quiz').show(); score = 0; currentQuestion = 0; showQuestion(); } function showProgress() { $('#currentQuestion').html(currentQuestion + " out of " + questions.length); } function showIsCorrect(isCorrect, question) { var result = "Wrong, the correct answer is " + question.answers[question.correct]; if (isCorrect) { result = "Correct"; } $('#isCorrect').html(result); } 
 * { padding: 0; margin: 0; box-sizing: border-box; text-decoration: none; text-align: center; background-color: #837F73; } h1 { font-family: 'Poor Story', cursive; background-color: #950002; padding: 60px; color: #FFAB0D; text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black; } h2 { font-family: 'Poor Story', cursive; font-size: 30px; padding: 60px; background-color: #950002; color: #FFAB0D; text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black; } p { font-family: 'Poor Story', cursive; background-color: #FFAB0D; font-size: 20px; font-weight: bold; } a { border: 1px solid #222F5B; padding: 10px; background-color: #222F5B; color: silver; border-radius: 5px; margin-top: 50px; display: inline-block; } a:hover { border: 1px solid #000000; background-color: #000000; color: #FCBF2B; } .quiz li { cursor: pointer; border: 1px solid; display: inline-block; width: 200px; margin: 10px; font-family: 'Poor Story', cursive; font-size: 26px; } #currentQuestion { color: #000000; font-size: 18px; font-family: 'Poor Story', cursive; margin-top: 10px; } #isCorrect { color: white; font-family: 'Poor Story', cursive; font-weight: bold; font-size: 18px; } .quiz, .summary { display: none; } .quiz ul { margin-top: 20px; list-style: none; padding: 0; } .selected { background-color: #398C3F; } 
 <!DOCTYPE html> <html> <head> <link href="https://fonts.googleapis.com/css?family=Poor+Story" rel="stylesheet"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <div class="start"> <h1>How Well Do You Know Harry Potter?</h1> <a href="#">Start Quiz</a> </div> <div class="quiz"> <h2>Question Title</h2> <ul> <li>Choice</li> <li>Choice</li> <li>Choice</li> <li>Choice</li> </ul> <a href="#">Submit Answer</a> <div id="currentQuestion"></div> <div id="isCorrect"></div> </div> <div class="summary"> <h2>Results</h2> <p>Thank you for taking the quiz! Here's how you scored. You answered x out of y correctly! Care to try again?</p> <a href="#">Retake Quiz</a> </div> <script src="https://code.jquery.com/jquery-3.1.0.js"></script> </body> </html> 

Added the changes needed for score updates as well: 还添加了分数更新所需的更改:

<!DOCTYPE html>
<html>

<head>
    <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
    <style>
        * {
            padding: 0;
            margin: 0;
            box-sizing: border-box;
            text-decoration: none;
            text-align: center;
            background-color: #837F73;
        }

        h1 {
            font-family: 'Poor Story', cursive;
            background-color: #950002;
            padding: 60px;
            color: #FFAB0D;
            text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
        }

        h2 {
            font-family: 'Poor Story', cursive;
            font-size: 30px;
            padding: 60px;
            background-color: #950002;
            color: #FFAB0D;
            text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
        }

        p {
            font-family: 'Poor Story', cursive;
            background-color: #FFAB0D;
            font-size: 20px;
            font-weight: bold;

        }

        a {
            border: 1px solid #222F5B;
            padding: 10px;
            background-color: #222F5B;
            color: silver;
            border-radius: 5px;
            margin-top: 50px;
            display: inline-block;
        }

        a:hover {
            border: 1px solid #000000;
            background-color: #000000;
            color: #FCBF2B;
        }

        .quiz li {
            cursor: pointer;
            border: 1px solid;
            display: inline-block;
            width: 200px;
            margin: 10px;
            font-family: 'Poor Story', cursive;
            font-size: 26px;
        }

        #currentQuestion {
            color: #000000;
            font-size: 18px;
            font-family: 'Poor Story', cursive;
            margin-top: 10px;

        }

        #isCorrect {
            color: white;
            font-family: 'Poor Story', cursive;
            font-weight: bold;
            font-size: 18px;

        }

        .quiz,
        .summary {
            display: none;
        }

        .quiz ul {
            margin-top: 20px;
            list-style: none;
            padding: 0;
        }

        .selected {
            background-color: #398C3F;
        }

        .wrong {
            background-color: red;
        }
    </style>
    <script>
        let score = 0;
        let currentQuestion = 0;
        let questions = [{
            title: "At what age was Harry Potter when he received his Hogwarts letter?",
            answers: ['7', '10', '11', '13'],
            correct: 1
        },
        {
            title: "Which is not a Hogwarts house?",
            answers: ['Dunder Mifflin', 'Ravenclaw', 'Slytherin', 'Gryffindor'],
            correct: 0
        },
        {
            title: "Who teaches Transfiguration at Hogwarts?",
            answers: ['Rubeus Hagrid', 'Albus Dumbledore', 'Severus Snape', 'Minerva McGonnagle'],
            correct: 3
        },
        {
            title: "Where is Hogwarts School for Witchcraft and Wizardry located?",
            answers: ['France', 'USA', 'UK', 'New Zealand'],
            correct: 2
        },
        {
            title: "What form does Harry Potter's patronus charm take?",
            answers: ['Stag', 'Eagle', 'Bear', 'Dragon'],
            correct: 0
        },
        {
            title: "What type of animal is Harry's pet?",
            answers: ['Dog', 'Owl', 'Cat', 'Snake'],
            correct: 1
        },
        {
            title: "Who is not a member of the Order of the Phoenix?",
            answers: ['Remus Lupin', 'Siruis Black', 'Lucious Malfoy', 'Severus Snape'],
            correct: 2
        },
        {
            title: "What is not a piece of the Deathly Hallows?",
            answers: ['Elder Wand', 'Cloak of Invisibility', 'Resurrection Stone', 'Sword of Gryffindor'],
            correct: 3
        },
        {
            title: "In which house is Harry sorted into after arriving at Hogwarts?",
            answers: ['Slytherin', 'Ravenclaw', 'Gryffindor', 'Hufflepuff'],
            correct: 2
        },
        {
            title: "What prevented Voldemort from being able to kill Harry Potter when he was a baby?",
            answers: ['Love', 'Anger', 'Friendship', 'Joy'],
            correct: 0
        },
        ];



        $(document).ready(function () {

            $('.start a').click(function (e) {
                e.preventDefault();
                $('.start').hide();
                $('.quiz').show();
                showQuestion();
            });

            $('.quiz ul').on('click', 'li', function () {
                $('.selected').removeClass('selected');
                $(this).addClass('selected');
            });

            $('.quiz a').click(function (e) {
                e.preventDefault();
                if ($('li.selected').length) {
                    let guess = parseInt($('li.selected').attr('id'));
                    let isCorrect = $('li.selected').attr('isCorrect');
                    checkAnswer(guess, isCorrect);
                } else {
                    alert('Please select an answer');
                }
            });

            $('.summary a').click(function (e) {
                e.preventDefault();
                restartQuiz();
            });

        });

        function showQuestion() {
            let question = questions[currentQuestion];
            $('.quiz h2').text(question.title);
            $('.quiz ul').html('');
            for (var i = 0; i < question.answers.length; i++) {
                $('.quiz ul').append(`<li isCorrect="true" id="${i}">${question.answers[i]}</li>`);
            }
            showProgress();
        }

        function showIncorrectQuestion(guess) {
            let question = questions[currentQuestion];
            $('.quiz h2').text(question.title);
            $('.quiz ul').html('');
            for (var i = 0; i < question.answers.length; i++) {
                let cls = i === question.correct ? "selected" : guess === i ? "wrong" : ""
                $('.quiz ul').append(`<li id="${i}" isCorrect="false" class="${cls}">${question.answers[i]}</li>`);
            }
            showProgress();
        }

        function checkAnswer(guess, isCorrect) {

            let question = questions[currentQuestion];
            if (question.correct === guess) {
                if (isCorrect === 'true') {
                    score++;
                }
                showIsCorrect(true);
                currentQuestion++;
                if (currentQuestion >= questions.length) {
                    showSummary();
                } else {
                    showQuestion();
                }
            } else {
                showIsCorrect(false);
                showIncorrectQuestion(guess);
            }


        }

        function showSummary() {
            $('.quiz').hide();
            $('.summary').show();
            $('.summary p').text("Thank you for taking the quiz! Here's how you scored. You answered " + score + " out of " + questions.length + " correctly! Care to try again?")
        }

        function restartQuiz() {
            $('.summary').hide();
            $('.quiz').show();
            score = 0;
            currentQuestion = 0;
            showQuestion();
        }

        function showProgress() {
            $('#currentQuestion').html(currentQuestion + " out of " + questions.length);
        }

        function showIsCorrect(isCorrect) {
            var result = "Wrong";
            if (isCorrect) {
                result = "Correct";
            }
            $('#isCorrect').html(result);
        }
    </script>



    <link href="https://fonts.googleapis.com/css?family=Poor+Story" rel="stylesheet">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>JS Bin</title>
</head>

<body>


    <div class="start">
        <h1>How Well Do You Know Harry Potter?</h1>
        <a href="#">Start Quiz</a>
    </div>


    <div class="quiz">
        <h2>Question Title</h2>
        <ul>
            <li>Choice</li>
            <li>Choice</li>
            <li>Choice</li>
            <li>Choice</li>
        </ul>
        <a href="#">Submit Answer</a>
        <div id="currentQuestion"></div>
        <div id="isCorrect"></div>
    </div>


    <div class="summary">
        <h2>Results</h2>
        <p>Thank you for taking the quiz! Here's how you scored. You answered x out of y correctly! Care to try again?</p>
        <a href="#">Retake Quiz</a>
    </div>




</body>

</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM