提问者:小点点

如何在Javascript测验中保存分数


我有一个关于Javascript和HTML的测试。一切正常。我关心的是,我需要保存高分的方式,其中他们将显示在另一个子页面。我真的不知道如何正确使用本地存储...我所知道的是它只能存储字符串,并且可以对对象进行字符串化。我试过下面的代码,但总是失败。

    this.score = 0;
    this.questions = questions;
    this.questionIndex = 0;
}

Quiz.prototype.getQuestionIndex = function() {
    return this.questions[this.questionIndex];
}

Quiz.prototype.guess = function(answer) {
    if(this.getQuestionIndex().isCorrectAnswer(answer)) {
        this.score++;
    var sound = new Audio();
    sound.src = "correct.mp3";
    }
    else {
    var sound = new Audio();
    sound.src = "wrong.mp3";

    }

    this.questionIndex++;
}

Quiz.prototype.isEnded = function() {
    return this.questionIndex === this.questions.length;
}

function Question(text, choices, answer) {
    this.text = text;
    this.choices = choices;
    this.answer = answer;
}

Question.prototype.isCorrectAnswer = function(choice) {
    return this.answer === choice;
}


function populate() {
    if(quiz.isEnded()) {
        showScores();
    }
    else {
        // show question
        var element = document.getElementById("question");
        element.innerHTML = quiz.getQuestionIndex().text;

        // show options
        var choices = quiz.getQuestionIndex().choices;
        for(var i = 0; i < choices.length; i++) {
            var element = document.getElementById("choice" + i);
            element.innerHTML = choices[i];
            guess("btn" + i, choices[i]);
        }

        showProgress();
    }
};

function guess(id, guess) {
    var button = document.getElementById(id);
    button.onclick = function() {
        quiz.guess(guess);
        populate();
    }
};

function showProgress() {
    var currentQuestionNumber = quiz.questionIndex + 1;
    var element = document.getElementById("progress");
    element.innerHTML = "Question " + currentQuestionNumber + " of " + quiz.questions.length;
};

function showScores() {
    var gameOverHTML = "<h1>Result</h1>";
    gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
    var element = document.getElementById("quiz");
    element.innerHTML = gameOverHTML;
};


// create questions here
var questions = [
    new Question("Which is not part of non-verbal communication?", ["Height", "Body Language", "Gestures", "Eye contact"], "Height"),
    new Question("What is vital for survival and it is one thing in life that we cannot avoid to do?", 
    ["Written Communication", "Human Communication", "Communication Climate", "Telephone Conversation"], "Human Communication"),
    new Question("It is the use of sounds and words to express yourself.", ["Verbal Communication", "Non-Verbal Communication", "Written Communication", "Visual Communication"], "Verbal Communication"),
    new Question("What refers to the one who initiates the communication?", ["Sender", "Receiver", "Noise", "Message"], "Sender"),
    new Question("What are means through which we transmit the message in either vocal or non-vocal messages?", ["Message", "Channel", "Sender", "Noise"], "Channel"),
    new Question("Which event requires verbal communication?", ["Calling someone on the phone", "Hurrying  to your classroom","Listening to a radio program", "Running to a track meet"],"Calling someone on the phone"),  
    new Question("All are examples of non-verbal communication except?", ["Reciting in class", "Frowning", "Hugging a friend", "Clapping"],"Reciting in class"),  
    new Question("It is the Latin word of communication.", ["Epikoinonía", "Communis", "La communication", "Komyunikēshon"], "Communis"),
    new Question("The word communication is derived from communis (Latin) which means?", ["Community","Message", "Common", "Oral Speech"],"Common"),
    new Question("Communicare means to _______", ["common", "care about many", "communicate", "make common to many", "comment"], "make")
];

// create quiz
var quiz = new Quiz(questions);

// display quiz
populate();


共1个答案

匿名用户

一个会帮助你的非常好的资源是下面的问题:

在HTML5本地存储中存储对象

var testObject = { 'one': 1, 'two': 2, 'three': 3 };

// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');

console.log('retrievedObject: ', JSON.parse(retrievedObject));

您可以拥有一个包含所有测验结果的数据结构。一旦一个新的测验完成,您就会得到结果,添加新的结果,然后再次保存。

示例(类似的东西):

let retrievedObject = JSON.parse(window.localStorage.getItem('results'));

if(!retrievedObject ){
alert('Empty, initializing');
retrievedObject  = [];
}

retrievedObject.push('quiz.results' + retrievedObject.length);
window.localStorage.setItem('results', JSON.stringify(retrievedObject));

此外,这里还有一个非常好的JSFiddle和一个关于使用LocalStorage的完整示例。

我添加了一些代码行来模拟将一个测验字符串添加到输出中。

https://jsfidle.net/menelaosbgr/6r23ejoq/4/