如果单击按钮1,2或3,我有一个可以更改按钮和面板文本的工作代码。 请参阅此codepen:http://codepen.io/anon/pen/GgKOba
我现在想要以这种方式使用本地存储:当您第一次访问该页面时,将显示默认文本。 单击按钮X后,按钮和面板文本将更改。 id存储在本地存储中。当您重新加载页面时,它会看到本地存储中的某些内容并使用它来更改按钮和面板文本。
我试过这种方式:http://codepen.io/anon/pen/JoPOQv
该codepen包含此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
});
});
正如你所看到的,我在google某个地方找到了一个if语句来检查本地存储是否为空,如果它没有执行某些规则。
但是你也可以看到它没有显示默认文本,也没有正确读取本地存储。 我做错了什么?
答案 0 :(得分:0)
你指的是错误的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
}