为什么刷新页面时 localStorage 条目会重置?

2023-12-29

我正在为我的班级制作一个猜谜游戏,我们应该实现一个本地存储的记分系统。我以为我理解了这个概念,但它并没有按照我想要的方式工作。当我玩游戏时,这些值存储在本地存储中,但是当我刷新时,这些值会重置......任何见解都会很棒!下面是我的脚本的开头,下面是我的 HTML 文件。

编辑:我将分数初始化为 1 的原因是,每当用户猜对时,就会添加 4 分(产生 +3),而当用户猜错时,会扣除 1​​ 分(产生 -2)。每点击一次重启按钮,用户就会再失去 1 分。

编辑2:为了更清楚起见,不妨粘贴我的脚本的其余部分:P

编辑3:JSfiddle 太棒了!http://jsfiddle.net/2pdaoeu6/ http://jsfiddle.net/2pdaoeu6/

'use strict';
//Define a container for the game, its variables and its methods.
var game = {
  answerPosition: 0,   // position of the current answer in the answersList - start at 0
  display: '',         // the current dash/guessed letters display - ex '-a-a--r--t'
  wrong: '',           // all the wrong letters guessed so far
  answer: '',          // the correct answer - one word from game.answersList
  wrongCount: 0,       // the number of wrong guesses so far
  over: false,         // is the game over?
  score: 1,            // 1 - 1 = 0
  answersList: [       // list of answers to cycle through
    'JavaScript',
    'document',
    'element',
    'ajax',
    'jQuery',
    'event',
    'json',
    'listener',
    'transition',
    'window'
  ]
};



game.restart = function () {

    localStorage.setItem('localScore', game.score - 1);
    var localScore =  Number(localStorage.getItem('localScore'));
    // var localScore = localStorage.localScore;

    // Initialize the game at the beginning or after restart
    // Initialize the game variables - the model
    game.answer = game.answersList[game.answerPosition].toLowerCase(); // get the word for this round
    // use the modulo operator to cycle through the answersList
    game.answerPosition = (game.answerPosition + 1) % game.answersList.length;
    game.display = game.dashes(game.answer.length);
    game.wrong = '';
    game.wrongCount = 0;
    game.over = false;
    game.score = localScore;

    // Initialize the web page (the view)
    $('progress').val('0');  // initialize the progress bar
    $('#display').text(game.display);
    $('#wrong').text('');
    $('#guessedletter').val('');
    $('#score').text(localScore); // initialize score


    // The focus method invoked on an input element allows the user to type in that input without having to click it.
    $('#guessedletter').focus();
};


game.play = function () {
    // Invoked when the user clicks on GUESS
    if (game.over) {// if the game is over
        $('#wrong').text('Press RESTART to play again.');  // user has to restart
    } else {
        //if the game is not over yet
        var guess = $('#guessedletter').val().toLowerCase();
        if (game.check(game.answer, guess)) {
            // if the guess is valid
            $('#display').text(game.display);
        } else if (guess) {
            // If it's a wrong non-empty guess 
            game.wrong = guess + ' ' + game.wrong;
            game.wrongCount++;
            $('#wrong') .text(game.wrong);
            $('progress').val(game.wrongCount);
        }
        // reinitialize the guess
        $('#guessedletter') .val('');
        $('#guessedletter').focus();
        // check for a win or loss
        game.outcome();
    }
};

game.dashes = function (number) {
    // this function takes a number as a parameter
    // and returns a string with that many dashes
    var result = '';
    for (var i = 1; i <= number; i++)  {
        result = result + '-';
    }
    return result;  
};

game.check = function (answer, letter) {
    // Checks all occurrences of the letter guessed against game.answer. 
    // Returns true if the guess is correct and false otherwise. 
    // Updates the game dash display variable game.display if applicable.
    var position;
    var result = false;
    if (letter) {   // check that guess is not the empty string
        // Find the first occurrence of guess in the answer
        position = game.answer.indexOf(letter);
        // if the guessed letter is found in the answer
        if (position > - 1) {
            result = true;
        }
        while (position >= 0) {
            // update the dash display and find all remaining occurrences
            game.display = game.display.substring(0, position) + letter + game.display.substring(position + 1);
            // get the next occurrence
            position = game.answer.indexOf(letter, position + 1);
        }
    }
    return result;
};

game.outcome = function () {
    // check if the game is won or lost
    if (game.answer === game.display) {
        $('#wrong') .text('Congratulations! You win! +3 points.');
        // game.score = (game.score + 4);
    game.score = Number(localStorage.getItem('localScore')) + 4;
        // localStorage['localScore'] = Number(localStorage.getItem('localScore')) + 4;
        game.over = true;  // game is over.  User has to restart to play again
        setTimeout(function(){game.restart()}, 3000);
    } else if (game.wrongCount >= 10) {
        $('#wrong') .text('No more guesses; the answer was: ' + game.answer
            + '! -2 points :(');
        // game.score = (game.score - 1);
        game.score = Number(localStorage.getItem('localScore')) - 1;
        // localStorage['localScore'] = Number(localStorage.getItem('localScore')) - 1;
        game.over = true;  // game is over.  User has to restart to play again
        setTimeout(function(){game.restart()}, 3000);
    }
};

// Main program starts here
$(document).ready(function () {
    game.restart();
    $('#guessbutton').click(game.play);
    $('#restart').click(game.restart);
});





<!DOCTYPE html>
<html>
    <head>
            <meta charset="utf-8">
            <title>Guessing Game</title>
        <link rel="stylesheet" type="text/css" href="guess.css" media="all">
    </head>
    <body>
        <h2>Guess a Letter</h2>    
        <p id="display" class="letters"></p>
        <input id="guessedletter" type="text" maxlength='1' class="letters" autofocus>
            <div>            
        <input id="guessbutton" type="button" value="GUESS">
        </div>
            <p>Wrong Letters</p>
        <p id="wrong" class="letters wrong"> </p>       
        <progress value="0" max="10"></progress>
            <div> 
        <input id="restart" type="button" value="RESTART">
            </div> 
         <p>Score: <span id="score"></span></p>
        <script defer src="../scripts/jquery-1.11.3.js"></script>
        <script defer src="../scripts/guess.js"></script>
    </body>
</html>

据我所知,你正在打电话game.restart()当您的应用程序加载时。在你的里面restart()方法,你正在这样做:

localStorage.setItem('localScore', game.score - 1);

当您的应用程序启动时,您正在重置localStorage key localScore每一次,你最后的分数都会消失。尝试检查一个值是否存在,如果存在,则跳过setItem, 像这样:

game.restart = function () {
    // if the localScore is not set, initialize it with your default value
    // otherwise don't set the localScore -> it would overwrite the saved values
    if(localStorage.getItem('localScore') === null) {
         localStorage.setItem('localScore', game.score - 1);
    }
    // .... rest of your function
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么刷新页面时 localStorage 条目会重置? 的相关文章

  • 使用 JavaScript 禁用第三方 cookie

    我正在努力根据所有在欧盟运营的公司的数据保护规则实施新的 Cookie 政策合规性 根据该规则 用户在使用任何网站时必须能够拒绝 接受除必需的 Cookie 之外的所有内容 在我客户的网站中 我可以看到正在存储以下第三方 cookie ga
  • 如何使用javascript将大图像转换为十六进制?

    如果我尝试将图像转换为十六进制 无论我使用哪个函数 我都会收到此错误消息 该图像的大小为 7 MB 19812 毫秒 清理 1401 2 1455 0 gt 1401 2 1455 0 MB 9 9 0 ms 自上次 GC 以来 8 3 m
  • 如何格式化 Highcharts 的 (x,y) 对数据的日期时间

    我的序列化方法会产生如下所示的日期时间字符串 2014 07 09T12 30 41Z 为什么下面的代码不起作用 function container highcharts xAxis type datetime series data x
  • 如何将内联 JavaScript 与 Express/Node.js 中动态生成的内容分开?

    对于具有几年 Web 开发经验但没有找到答案的人来说 这是一个有点菜鸟的问题程序员堆栈交换 or Google 我决定在这里问一下 我在用Express网络框架Node js 但这个问题并不特定于任何 Web 框架或编程语言 以下是从数据库
  • 隐藏 Div 的父级

    我只是想隐藏父divcomments section div class content content green div div div 我试过这个 document getElementById comments section pa
  • 有没有办法使用 Rspec/Capybara/Selenium 将 javascript console.errors 打印到终端?

    当我运行 rspec 时 是否可以让 capybara selenium 向 rspec 报告任何 javascript console errors 和其他异常 我有一大堆测试失败 但当我手动测试它时 我的应用程序正在运行 如果不知道仅在
  • HTML5 MediaSource 适用于某些 mp4 文件,但不适用于其他文件(相同的编解码器)

    我正在玩 MediaSource API 代码直接取自 Mozilla 的示例页面 https developer mozilla org en US docs Web API MediaSource endOfStream https d
  • 如何解决 Typescript 构建中的错误“找不到模块 'jquery'”

    我目前在 ts 文件的顶部有这个import require jquery 我这样做是因为我试图在我的打字稿文件中使用 jquery 但我似乎无法编译它 因为它返回标题中所述的错误 我正在使用 ASP NET CORE 脚本文件夹 tsco
  • 检查 jQuery 1.7 中是否存在基于文本的选择选项

    所以我有以下 HTML 片段
  • 有没有办法在 onclick 触发时禁用 iPad/iPhone 上的闪烁/闪烁?

    所以我有一个有 onclick 事件的区域 在常规浏览器上单击时 它不会显示任何视觉变化 但在 iPad iPhone 上单击时 它会闪烁 闪烁 有什么办法可以阻止它在 iPad iPhone 上执行此操作吗 这是一个与我正在做的类似的示例
  • 不可勾选的单选按钮与专有的复选框

    从 UI 角度来看 是拥有一组具有取消选中功能的单选按钮更好 还是拥有一组独占的复选框 意味着一次只能选中一个 更好 Update 我没想到对此会有如此负面的反应 如果我给出一个更接近其使用方式的示例 也许会有所帮助 我有一个充满数据绑定内
  • Firebase 函数 onWrite 未被调用

    我正在尝试使用 Firebase 函数实现一个触发器 该触发器会复制数据库中的一些数据 我想观看所有添加的内容votes user vote 结构为 我尝试的代码是 const functions require firebase func
  • 从数据库检查数据的异步解决方案各种循环子句

    我想要做的是异步检查数据库并从中获取结果 在我的应用程序中我试图实现Asynchronously将此步骤解决为 从数据库中检查手机号码JsonArray循环子句的种类 Create JsonArray从结果 打印创建的数组 我学到了足够多的
  • 在移动设备上滚动

    这个问题更多的是一个建议研究 我确实希望它对其他人有帮助 并且它不会关闭 因为我不太确定在哪里寻求有关此事的建议 在过去的 6 个月里 我一直在进行移动开发 我有机会处理各种设备上的各种情况和错误 最麻烦的是滚动问题 当涉及到在网站的多个区
  • Vue 和 Vuex:处理依赖的计算属性

    我的应用程序是一个使用 Vuex 在 Vue 中构建的精简电子表格 关键组件是TableCollection Table and Row The TableCollection有一个包含多个的数组Table对象 每个Table有一个包含多个
  • 在 Shopify 商店中嵌入 Vue 组件

    在产品页面中 我尝试显示自定义 Vue 组件 为简洁起见 该组件根据给定的产品 ID 显示 Firebase 数据库中的一些信息 我最初尝试将其制作为 Shopify 应用程序 以便我可以访问他们的 API 我实现了 OAuth 并且可以检
  • 带参数的事件监听器

    我想将参数传递给 JavaScript 中的事件侦听器 我已经找到了解决方案 但我无法理解它们为什么或如何工作以及为什么其他解决方案不起作用 我有 C C 背景 但是 Javascript 函数的执行有很大不同 您能否帮助我理解以下示例如何
  • JavaScript 相对路径

    在第一个 html 文件中 我使用了一个变量类别链接 var categoryLinks Career prospects http localhost Landa DirectManagers 511 HelenaChechik Dim0
  • 如何确定所有角度2分量都已渲染?

    当所有 Angular2 组件完成渲染时 是否会触发一个角度事件 For jQuery 我们可以用 function 然而 对于 Angular2 当domready事件被触发 html 只包含角度组件标签 每个组件完成渲染后 domrea
  • CSS溢出文本显示在几行中,没有断字

    我有一些长文本显示在 div 中 该 div 具有固定的宽度和高度 我希望文本显示在几行上 作为 div 高度 并且句子单词不会中断 一行中的单词前缀和下一行中的继续 此外 我想在末尾添加省略号最后一句话 CSS white space n

随机推荐

  • 将 3d 4x4 旋转矩阵转换为 2d

    假设我们有一个 4x4 矩阵 其索引如下 00 01 02 03 10 11 12 13 20 21 22 23 30 31 32 33 如何将该矩阵中包含的旋转数据 忽略 z 轴 如果有帮助的话 转换为单个 2d 旋转角度 以弧度为单位
  • VSTS 缺少某些构建标志:env:BUILD_SOURCEVERSIONMESSAGE

    在我的 Visual Studio Team Services 构建中 我从 bitbucket 存储库中提取 我正在尝试获取提交消息并在 powershell 脚本中使用它 在我的 powershell 脚本中 我有以下代码 param
  • 不明白这个 TypeError: 'list' object is not callable

    我有一个名为im py其中包含几个函数和几个类 第一个函数和类失败了 TypeError list object is not callable 问题似乎是在函数中创建的列表的第一个元素 然后将其传递给类 列表的大部分可以由类处理 但第一个
  • 如何在 C# 中使用管道和 let 参数进行 $lookup (MongoDB.Driver 2.7.2)

    我需要在我的 C 代码中在 MongoDB 中运行以下查询 我使用 MongoDB Driver 2 7 2 和 MongoDB 4 0 我想使用 lookup 而不是 project unwind 以防止命名集合的每个可能字段 db ge
  • std::initializer_list 的实现

    我一直在研究如何initializer list已实现 所以我找到了标准的第 18 9 节 并找到了一个看起来足够简单的界面 我认为制作我自己的版本 我命名为 会很有启发性MyNamespace InitializerList和一个用例 t
  • 在mfc中如何将控件置于前面

    如何更改 MFC 中控件的 Z 顺序在设计时 即我无法使用 SetWindowPos 或在运行时执行此操作 我想在设计器中查看更改后的 z 顺序 即使我必须诉诸直接编辑 rc 代码 我有一个 MFC 对话框 要向其中添加控件 如果控件的边缘
  • 在 tvOS 上对 Dropbox 进行身份验证

    我在我的 ios 移动应用程序中使用 dropbox sdk 它使用 dropbox 身份验证从我的应用程序中的 dropbox 中获取用户文件 它在我的 ios 应用程序上完美运行 并上传到苹果商店 我想让它也适用于 tvos 苹果商店
  • EC2 上的轻度、中度或重度利用率预留实例之间有什么区别?

    他们讨论了不同的利用率实例 但除了价格之外 我找不到任何一个地方可以实际说明轻利用率大型实例和重利用率大型实例之间的区别 有人可以告诉我有什么区别吗 实例是相同的 这只是价格差异 因此如果您知道自己将大量使用该实例 则可以通过支付预付费用来
  • Mandelbrot 集渲染的平滑频谱

    我目前正在编写一个程序来生成非常巨大的 65536x65536 像素及以上 Mandelbrot 图像 我想设计一个光谱和着色方案来使它们公正 这维基百科精选曼德尔布罗图像 http en wikipedia org wiki File M
  • 最有效的多重纹理方法 - iOS、OpenGL ES2、优化

    我正在尝试找到在 iOS 上处理 OpenGL ES2 中多重纹理的最有效方法 我所说的 高效 是指即使在较旧的 iOS 设备 iPhone 4 及更高版本 上也能实现最快的渲染 但同时还要平衡便利性 我考虑过 并尝试过 几种不同的方法 但
  • 单个 Logger 的每个附加程序的日志级别

    是否可以根据appender为单个Logger配置不同的日志级别 我意识到这与此类似question https stackoverflow com questions 1839647 how to configure log4j to l
  • 何时在 Spring 中使用自动装配

    我正在看书专业春季3 https rads stackoverflow com amzn click com 1430241071 其中有一段确实让我很困惑 该段落是关于 Spring 中的自动装配 以下是摘录 在大多数情况下 是否应该使用
  • 合成器外观和感觉中的默认按钮输入映射?

    我正在尝试使用 UIManager 获取并清除一些默认键绑定 以便空格键不会激活我的 JButtons 如所解释的here https stackoverflow com questions 12133795 removing defaul
  • strtok()函数的实现

    我需要编写我的函数 strtok 下面是我的代码 问题是 我无法显示结果字符串 在我使用的代码中strcpy 然后显示新数组 是否可以仅使用指针显示字符串 str include
  • 使用 Spring DispatcherServlet 自定义 404

    我已设置 web xml 如下 我还有一个基于注释的控制器 它接受任何 URL 模式 然后转到相应的 jsp 我已在 servlet xml 中进行了设置 但是 如果我转到以 html 结尾的页面 并且其 jsp 不存在 我不会看到自定义
  • Selenium 访问框架内的元素时出现问题

    我在验证由框架集和框架组成的页面中的元素时遇到问题 我正在使用代码 selenium selectFrame relative up selenium selectFrame topFrame 但它失败并出现错误 未找到元素 topFram
  • J2ME 支持 HTTP PUT 吗?

    我刚刚注意到 MIDP 2 0 API 中的一个奇怪的事情 HttpConnection 类 apidocs 明确引用了方法 GET POST 和 HEAD 但没有其他方法 这是否意味着它们不受支持 http java sun com ja
  • 如何在 powershell 中列出所有已安装、可运行的 cmdlet?

    我想列出 powershell 中所有已安装 可运行的 cmdlet 和函数 但是Get Command正在列出以某种方式 存在 但未加载且不可运行的 cmdlet 举个例子 Get Command lists New IseSnippet
  • 使用 Gmail Python 发送电子邮件

    我正在尝试发送电子邮件 但遇到此错误 smtplib SMTPAuthenticationError 534 b 5 7 9 Application specific password required Learn more at n5 7
  • 为什么刷新页面时 localStorage 条目会重置?

    我正在为我的班级制作一个猜谜游戏 我们应该实现一个本地存储的记分系统 我以为我理解了这个概念 但它并没有按照我想要的方式工作 当我玩游戏时 这些值存储在本地存储中 但是当我刷新时 这些值会重置 任何见解都会很棒 下面是我的脚本的开头 下面是