簡體   English   中英

Javascript 問答游戲

[英]Javascript Quiz Game

我正在嘗試為家庭作業創建一個基本的 javascript 測驗,但我很難在單擊時注冊正確/不正確的答案。 我只是不斷收到“答案”未定義的錯誤。 我不確定我應該如何以不同於我在“if”語句中所做的來定位答案索引。 任何幫助表示贊賞。

 $(document).ready(function() { var correctAnswers = 0; var incorrectAnswers = 0; var unansweredCounter = 0; var questionIndex = 0; var intervalId; var clockRunning = false; var t = 15; $("button").click(startTimer); function startTimer() { if (!clockRunning) { t = 15; intervalId = setInterval(decrement, 1000); clockRunning = true; } } function decrement() { t--; $(".timer").html("<h1>" + t + "</h1>"); if (t === 0) { stop(); } } function stop() { clearInterval(intervalId); clockRunning = false; } var questions = [{ question: "whats the weather?", choices: ["who cares", "cloudy", "eclipse"], answer: 0 }, { question: "do you like coding?", choices: ["getting there", "sometimes", "totally"], answer: 0 }, { question: "do you like video games?", choices: ["love", "hate", "sometimes"], answer: 0 }, { question: "do you like sports?", choices: ["yes", "sometimes", "no"], answer: 0 }, { question: "do you like food?", choices: ["the best", "yeah", "totally"], answer: 0 }]; function postQuestion(post) { if (questionIndex < questions.length) { $(".questions").html("<h1>" + questions[post].question + "</h1>"); for (var i = 0; i < questions[post].choices.length; i++) { var newDiv = $("<div>"); newDiv.addClass("snickleFritz").attr("numberIndex", i).text(questions[post].choices[i]); $(".choices").append(newDiv); } } $(".snickleFritz").on("click", function() { console.log(this); var userChoice = $(this).attr("numberIndex"); userChoice = parseInt(userChoice); if (userChoice === questions[questionIndex].answer) { correctAnswers++; questionIndex++; } else { incorrectAnswers++; questionIndex++; } }) } postQuestion(questionIndex); $(".wins").html("<h1>" + correctAnswers + "</h1>"); $(".losses").html("<h1>" + incorrectAnswers + "</h1>"); });
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div class="timer"></div> <div class="questions"></div> <div class="choices"></div> <button>Start</button> <div class="wins"></div> <div class="losses"></div> <div class="unanswered"></div> <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> <script type="text/javascript" src="moreTrivia.js"></script> </body> </html>

因為這是一項任務,所以我不會給你一個直接的代碼,但會指出你所缺少的:

  1. 在將新問題的選項附加到它之前清除.choices
  2. questionIndex++移動到 onClick 函數的末尾
  3. 運行postQuestion(questionIndex); 在 onClick 函數中增加questionIndex之后,就會彈出一個新問題
  4. 在 onClick 函數的末尾,更新.wins.losses div - 這將顯示更新后的值

為了改進的目的,我建議像下面這樣構造代碼。 以這種方式使用對象使代碼更具可讀性,應用程序更具可擴展性。

 var questions = { index:0, new: function() { if (questions.index < questionsdb.length) { $(".questions span").text(questionsdb[this.index].question); $(".choices ul").html(''); for (const choice of questionsdb[questions.index].choices) { $(".choices ul").append('<li class="snickleFritz" numberIndex="'+questionsdb[this.index].choices.indexOf(choice)+'"><h2>'+choice+'</h2></li>'); } timer.start(15); } else {return;} } } var answers = { correct:0, incorrect:0, unanswered:0, markCorrect: function() { answers.correct++; $(".wins h1").text(answers.correct); questions.index++; questions.new(); }, markFalse: function() { answers.incorrect++; $(".losses h1").text(answers.incorrect); questions.index++; questions.new(); }, markUnanswered: function() { answers.unanswered++; $(".unanswered h1").text(answers.unanswered); questions.index++; questions.new(); } }; var timer = { intervalId: 0, running: false, t: 15, start: function(seconds) { if (!timer.running) { timer.t = seconds; timer.intervalId = setInterval(timer.decrement, 1000); timer.running = true; } }, decrement: function() { timer.t--; $(".timer #sec").text(timer.t); if (timer.t === 0) { timer.stop(); answers.markUnanswered(); } }, stop: function() { clearInterval(timer.intervalId); timer.running = false; } }; $(document).on('click','.snickleFritz', function() { timer.stop(); if( questions.index >= questionsdb.length ) {return;} var userChoice = Number($(this).attr("numberindex")); if (userChoice === questionsdb[questions.index].answer) { answers.markCorrect(); } else { answers.markFalse(); } }); $('button').click(function() { questions.new() }); var questionsdb = [{ question: "whats the weather?", choices: ["who cares", "cloudy", "eclipse"], answer: 0 }, { question: "do you like coding?", choices: ["getting there", "sometimes", "totally"], answer: 0 }, { question: "do you like video games?", choices: ["love", "hate", "sometimes"], answer: 0 }, { question: "do you like sports?", choices: ["yes", "sometimes", "no"], answer: 0 }, { question: "do you like food?", choices: ["the best", "yeah", "totally"], answer: 0 }];
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button>Start</button> <div class="timer"><h1>Seconds left: <span id="sec"></span></h1></div> <div class="questions"><h1>Question: <span></span></h1></div> <div class="choices"><ul></ul></div> <div class="wins">Correct:<h1>0</h1></div> <div class="losses">Incorrect:<h1>0</h1></div> <div class="unanswered">Unanswered:<h1></h1></div>

檢查這個簡單的 javascript 測驗以獲取想法。 我的任務是測驗只有“真”或“假”兩個答案。 下一步按鈕僅在您選擇一個后才會出現。

https://codepen.io/gretakavaliauskaite/pen/zYKPMOe

 var pos = 0, correct = 0, quiz, quiz_status, question, chA, chB, correctAnswer, wrongAnswer; var False = "False"; var True = "True"; var executed = false; var questions = [ { question: "The oldest cat lived 30 years", a: "True", b: "False", answer: "False", correctAnswer: "You were right. The oldest cat on record was Crème Puff from Austin, Texas, who lived from 1967 to 2005, which is 38 years. A cat typically can live up to 20 years, which is equivalent to about 96 human years.", wrongAnswer: "Wrong choice... The oldest cat on record was Crème Puff from Austin, Texas, who lived from 1967 to 2005, which is 38 years. A cat typically can live up to 20 years, which is equivalent to about 96 human years." }, { question: "A cat's jaw can move sideways", a: "True", b: "False", answer: "False", correctAnswer: "Correct! A cat's jaw can't move sideways, so a cat can't chew large chunks of food.", wrongAnswer: "Wrong choice... A cat's jaw can't move sideways, so a cat can't chew large chunks of food." }, { question: "Cats make about 100 different sounds.", a: "True", b: "False", answer: "True", correctAnswer: "Correct! Cats make about 100 different sounds. Dogs make only about 10.", wrongAnswer: "Wrong Choice... Cats make about 100 different sounds. Dogs make only about 10." }, { question: "A cat can climb head first down a tree.", a: "True", b: "False", answer: "False", correctAnswer: "Correct! A cat can't climb head first down a tree because every claw on a cat's paw points the same way. To get down from a tree, a cat must back down.", wrongAnswer: "Wrong Choice... A cat can't climb head first down a tree because every claw on a cat's paw points the same way. To get down from a tree, a cat must back down." }, { question: "A cat's hearing is better than a dog's.", a: "True", b: "False", answer: "True", correctAnswer: "Correct! A cat's hearing is better than a dog's. And a cat can hear high-frequency sounds up to two octaves higher than a human.", wrongAnswer: "Wrong Choice... A cat's hearing is better than a dog's. And a cat can hear high-frequency sounds up to two octaves higher than a human." } ]; // this function renders a question on the page function renderQuestion() { quiz = document.getElementById("quiz"); if (pos >= questions.length) { quiz.innerHTML = "<h3>You got " + correct + " of " + questions.length + " questions correct</h3><label><input type='button' class='btn btn-outline-success mt-1' value='Start again' onclick='renderQuestion()'></label>"; document.getElementById("quiz_status").innerHTML = "Quiz completed"; // resets the variable to allow users to restart the quiz pos = 0; correct = 0; // stops rest of renderQuestion function running when quiz is completed return false; } document.getElementById("quiz_status").innerHTML = "Question " + (pos + 1) + " of " + questions.length; question = questions[pos].question; chA = questions[pos].a; chB = questions[pos].b; correctAnswer = questions[pos].correctAnswer; wrongAnswer = questions[pos].wrongAnswer; // display the question quiz.innerHTML = "<h3>" + question + "</h3>"; // display the answer options quiz.innerHTML += "<label> <input type='button' class='btn btn-outline-secondary m-1' value='" + chA + "' onclick='checkAnswer(" + chA + ")'></label>"; quiz.innerHTML += "<label> <input type='button' class='btn btn-outline-secondary m-1' value='" + chB + "' onclick='checkAnswer(" + chB + ")'></label>"; executed = false; } function checkAnswer(answer) { // checks if answer matches the correct choice if (!executed) { if (answer == questions[pos].answer) { //each time there is a correct answer this value increases correct++; quiz.innerHTML += "<div class='bg-success p-2 mt-2 br-5'><p>" + correctAnswer + "</p><button onclick='renderQuestion()' class='btn btn-outline-light'>Next</button></div>"; executed = true; } else { quiz.innerHTML += "<div class='bg-danger p-2 mt-2 br-5'><p>" + wrongAnswer + "</p><button onclick='renderQuestion()' class='btn btn-outline-light'>Next</button></div>"; executed = true; } pos++; } } function startQuiz() { renderQuestion(); document.getElementById("quiz-intro").classList.add("hide"); document.getElementById("quiz-content").classList.remove("hide"); }
 .hide { display: none; } #quiz-intro, #quiz-content { border: 1px solid green; } .br-5 { border-radius: 5px; } #quiz p { color: white; }
 <html> <head> <title>Cat Quiz</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> </head> <body> <div class="container mt-4"> <div class"row"> <div class="col-12 col-sm-7"> <div id="quiz-intro" class="p-3 br-5"> <h2>How much you know about cats?</h2> <button type="button" class="btn btn-outline-success mt-2" onclick="startQuiz()">Start Quiz</button> </div> <div id="quiz-content" class="hide p-3 br-5"> <p id="quiz_status"></p> <div id="quiz"></div> </div> </div> </div> </div> </body> </html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM