本地存储,简单的方式
local-storage, the simple way
我有一个工作代码,如果单击按钮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语句来检查本地存储是否为空,以及它是否没有执行一些规则。
但正如您所看到的,它没有显示默认文本,也没有正确读取本地存储。我做错了什么?
您指的是错误的id
。this.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
}
相关文章:
- 简单的Javascript方式,在输入字段的每5位数字后添加一个空格
- Javascript使用加载gif的最简单/最优雅的方式
- 如何以非常简单的方式在 JavaScript 中打印星形图案
- 如何在jQuery中以最简单的方式进行调试
- 最简单的实现方式是网页上的动态更新表(java/css)
- 如何以简单的方式将函数转换为 RequireJS 中的模块
- 以简单的方式将多个数据变量传递给 AJAX 函数
- 如何以简单的方式将像素转换为em
- 通过Facebook API发送朋友的生日提醒电子邮件的最简单且免费的方式
- 本地存储,简单的方式
- 使用AngularJS和TypeScript以简单的方式引用
- 如何使用html2canvas和jspdf以正确而简单的方式导出为pdf
- 寻找JavaScript和Java之间的简单通信方式
- 指定简单配置文件HTML或javascript的最佳方式是什么
- 以更简单的方式合并JSON
- 咆哮的工作方式简单,但不是困难的方式,方块
- IE是否有像Chrome、FF、Safari和Opera那样的简单的、javascript驱动的扩展开发方式?
- 简单的javascript for循环没有按照我认为的方式运行
- 如何以更简单的方式正确填写这张表格
- 简单可靠的方式来检查用户是否登录或不使用javascript [ForumMotion]