1

Html 代码 index.html 这是我的 html 代码,我只是放了按钮和文本输入。即使我们刷新它,我也想在页面上获取文本输入值(意味着旧的 vaue 保留在页面上)

<div id="result">div</div> 
<input type="text" id="tt" />
<button id="btn" onClick="calls()">submit</button>

这是脚本代码,我将此代码用于本地存储,但在页面刷新后它不起作用。

function calls()
{
if(typeof(Storage)!=="undefined")
  {


  localStorage.lastname=document.getElementById("tt").value; ;
  document.getElementById("result").innerHTML="Last name: " + localStorage.lastname;
  }
else
  {
  document.getElementById("result").innerHTML="Sorry, your browser does not support web     storage...";

  }}
4

3 回答 3

1

如果您使用 jquery,那么您可以像这样轻松访问本地存储

localStorage["check"] = 1;

刷新页面后,您将获得相同的值

alert(localStorage["check"]);
于 2013-06-11T15:36:21.193 回答
0

Yes, loading the file locally means that it doesn't have an origin. Since localStorage is uses the same-origin policy to determine access to stored data, it is undefined what happens when you use it with local files, and likely that it won't be persisted.

You will need to host your file on a web server in order to have a proper origin; you can just run Apache or any other server locally and access it via localhost.

Taken from: localStorage doesn't retrieve values after page refresh

于 2013-06-11T15:31:45.433 回答
0

如果您已经在使用 jQuery,我很想建议您使用 cahartl 的 jquery cookie 插件 - 例如,我们一直在将它用于小型教育活动中,学生需要在页面之间切换,并且效果非常好.

GitHub链接

于 2013-06-12T14:31:54.630 回答