Javascript测验游戏

时间:2017-08-24 04:23:24

标签: javascript jquery

我正在尝试为家庭作业创建一个基本的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>

3 个答案:

答案 0 :(得分:0)

因为这是一项任务,我不会给你一个直接的代码,但会指出你缺少的东西:

  1. 在向其添加新问题的选项之前清除.choices
  2. questionIndex++移至onClick功能的末尾
  3. 在onClick函数中增加postQuestion(questionIndex);后立即运行questionIndex,以便弹出新问题
  4. 在onClick函数的最后,更新.wins.losses div - 这将显示更新后的值

答案 1 :(得分:0)

出于改进的目的,我建议构建如下代码。以这种方式使用对象使代码更具可读性,并且应用程序更具可扩展性。

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>

答案 2 :(得分:0)

检查这个简单的 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>