当前位置: 首页 > 知识库问答 >
问题:

如何在Javascript测验中保存分数

顾俊楚
2023-03-14

我有一个关于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个答案

严远
2023-03-14

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

在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/

 类似资料:
  • 问题内容: 大家好:)我有一个评分栏,它可以正常工作,但是当用户离开页面时,该评分不会保存。您如何保存用户评分? 这是代码 任何帮助,将不胜感激。 问题答案: 您可以为此使用 SharedPreferences 。 返回应用程序之前,请保存评级,然后从中检索评级并在评级栏中进行设置。 保存值 您可以 检索 类似 的值 其中 的myKey 是 键名 ,通过它可以识别值.. 编辑 像这样更改代码 而当

  • 我有一个有效的javascript测验。目的是保存用户的分数。 这就是我所拥有的。在测验(quiz.html)结束时,弹出一个警报,并显示用户的分数(这工作很好)。关闭警告框后,将出现一个新窗口complete.html(这也起作用)。 在我的complete.html中,我有以下代码。 但是,我尝试使用,但是分数没有出现在SPAN#quiztotalscore中。我错过什么了吗?我是否需要先将分

  • 正如你看到我的问题,我很困惑,因为我看到了许多文章和条纹文档解决方案,每次我得到不同的东西。我的应用程序流程类似于第一个用户,他将有两个选项 以前保存的卡片 输入新卡 在这样做的时候,我从客户那里获取卡的详细信息,然后我生成令牌并发送将从db获取的令牌和CusterId(如果是老客户),这意味着客户已经生成,在后端,我首先使用添加付款信息后获得的条带令牌创建客户(如果没有找到CusterId),然

  • 我对node js和expressjs框架很陌生。我正在开发一个web应用程序,我被卡住了。我已经设置了所有的数据库要求,所有的工作都很好,现在我想把一些数据保存到数据库中,我把数据存储在一个变量中,但不幸的是,存储在变量(MyID)中的数据没有保存。这是我的密码 var=MyID app.post(“/AddContact”,function(req,res){ }

  • 比如接口有很多,都带一个token,但是某一个接口返回token失效了。我本地刷新token后,需要重试之前的接口,这个要怎么实现。 接口有地址,有参数;是个方法,不想路由是个字符串,可以存一下。

  • 警告:容器被设计为无状态的实例,任何需要持久化的数据,请采用数据库或文件系统保存在容器实例之外,我们不对保存在容器内的数据提供任何保障。当 DaoCloud 需要迁移,或用户扩容容器资源时,容器内的数据将会遗失,并且无法找回。 使用数据库服务 DaoCloud 在服务集成模块中提供了 MySQL、Redis、MongoDB、InfluxDB 等数据服务,如您需要做内容的持久化保存,可以选择使用 M