本地存储,简单的方式

local-storage, the simple way

本文关键字:方式 简单 存储      更新时间:2023-09-26

我有一个工作代码,如果单击按钮1、2或3,它会更改按钮和面板的文本。请参阅此代码笔:http://codepen.io/anon/pen/GgKOba

我现在想用这种方式使用本地存储:当你第一次访问页面时,会显示默认文本。单击按钮X后,按钮和面板文本将发生更改。id存储在本地存储器中。当你重新加载页面时,它会看到本地存储中有东西,并使用它来更改按钮和面板文本。

我是这样尝试的:http://codepen.io/anon/pen/JoPOQv

这个代码笔包含这个html:

<div data-role="panel" id="panel"> 
    <h2>Panel Header</h2>
    <p>default text</p>
</div> <!-- /panel -->
<div class="container">
  <a href="#panel" class="ui-btn ui-btn-inline ui-corner-all ui-shadow" id="panel_button"> <p>default text</p></a>
</div>
<div class="container">
  <a href="#tt_popup" data-role="button" data-rel="popup" class="ui-btn ui-btn-inline ui-corner-all btn" id="btn1" data-transition="flip">Button 1</a>

这个javascript:

// if we have something on local storage 
if(localStorage.getItem('id')) {
$("#panel p").html("This is info about stop <b>" + this.id + "</b>."); //then set this html text to the panel p
      $("#panel_button p").html("Info about stop " + this.id + "."); // and change the button text
}
$(document).on("ready", function () {
    $(".btn").on("click", function () { //if a button with class btn is clicked
      $("#panel p").html("This is info about stop <b>" + this.id + "</b>."); //then set this html text to the panel p
      $("#panel_button p").html("Info about stop " + this.id + "."); // and change the button text
      localStorage.setItem('id', this.id);        //also add the last-clicked id to the local-storage
    });
});

正如你所看到的,我使用了我在谷歌某处找到的if语句来检查本地存储是否为空,以及它是否没有执行一些规则。

但正如您所看到的,它没有显示默认文本,也没有正确读取本地存储。我做错了什么?

您指的是错误的idthis.id不是您从localStorage获得的id。为您修复:

// if we have something on local storage
var id = localStorage.getItem('id');
if(id) {
    $("#panel p").html("This is info about stop <b>" + id + "</b>."); //then set this html text to the panel p
    $("#panel_button p").html("Info about stop " + id + "."); // and change the button text
}