简单的 Javascript 测验(全局变量有问题?) [英] Simple Javascript Quiz (trouble with global variables?)

查看:26
本文介绍了简单的 Javascript 测验(全局变量有问题?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一个简单的 javascript 测验,但很难计算得分.我是 javascript 初学者,所以请耐心等待.我正在创建一个测验,在新页面上有一个新问题,最后一页显示分数.目前,当我回答问题并转到下一页时,分数会重置.这可能是我正在使用的变量,但我对 javascript 了解不够,无法修复它.

I'm trying to make a simple javascript quiz, but its been difficult figuring out the scoring. I'm a beginner with javascript so bear with me. I'm creating a quiz that has a new question on a new page and the last page displays the score. Currently when I answer a question and go to the next page and the score resets. It's probably the variable I'm using but I don't know enough about javascript to fix it.

我有四个按钮,一个正确答案和三个错误答案.正确答案触发和函数将 1 添加到变量 x,即分数.变量 x 是一个全局变量.所以当我进入下一页查看分数时,分数重置为 0.

I have four buttons, one correct answer and three incorrect answers. The correct answer triggers and function that adds 1 to the variable x which is the score. The variable x is a global variable. So when I go to the next page to see the score the score resets at 0.

如果可能,我正在尝试找到解决此问题的简单方法.我将这篇文章的代码压缩到一页,但分数假设打印下一页而不是问题页.感谢所有阅读本文的人!

I'm trying to find a simple solution to this issue if possible. I condensed the code to one page for this post but the score is suppose to print the next page not the question page. Thank you to all who reads this!

var x = 0;

function myFunctionCorrect() {
  x = x + 1;
  document.getElementById("demo").innerHTML = "Correct!";
  document.getElementById("scoretext").innerHTML = "Your score is " + x + ".";
}

function myFunctionWrong() {
  document.getElementById("demo").innerHTML = "Wrong!";
}

<button onclick="myFunctionCorrect()" class="elementbutton">Spandrel</button>
<button onclick="myFunctionWrong()" class="elementbutton">Attic</button>
<button onclick="myFunctionWrong()" class="elementbutton">Roundrel</button>
<button onclick="myFunctionWrong()" class="elementbutton">Plinth</button>
   
<p id="demo"></p>
<p id="scoretext"></p>

推荐答案

var x = 0;
function myFunctionCorrect() {
  x = x + 1;
  localStorage.setItem("score", x);
}

function showScore() {
var score=localStorage.getItem("score")
document.getElementById("scoretext").innerHTML = "Your score is " + score + ".";
      
}

你必须做这样的事情你的 myFunctionCorrect 应该将值存储在 local-storage 中,然后像 showScore 这样的函数可以从 localstorage 检索分数并显示给用户.

You have to do something like this your myFunctionCorrect should store the value in local-storage and then a function like showScore can retrieve the score from localstorage and show to user.

这篇关于简单的 Javascript 测验(全局变量有问题?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆