我对Javascript和HTML进行了测验。一切正常。我担心的是,我需要以某种方式保存高分,以便将其显示在另一个子页面中。我真的不知道如何正确使用localStorage ...我只知道它只能存储字符串,并且可以对对象进行字符串化。我尝试了以下代码,但是我总是失败。

    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();

最佳答案

以下问题是一个非常有用的资源,它将对您有帮助:

Storing Objects in HTML5 localStorage

这是本地存储基本用法的示例:

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://jsfiddle.net/menelaosbgr/6r23ejoq/4/

关于javascript - 如何在Java测验中保存分数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60037063/

10-11 23:39