admin管理员组

文章数量:1335380

I am using HTML5 local storage for the first time using FF5. I have the below javascript, it should save a string into local storage, however when the page is reloaded there isn't any values in local storage. What am I doing wrong? Why is 'foo' not populated on the pages sedond load?

 <script src=".4.2/jquery.min.js</script>

<script>
$(document).ready(function() {

if (!localStorage) {return false; }

var foo = localStorage.getItem("key1");

if (foo != null)
{
   document.getByName("identifier").value = foo;
}

localStorage["key1"] = "value1";

});
</script>

I am using HTML5 local storage for the first time using FF5. I have the below javascript, it should save a string into local storage, however when the page is reloaded there isn't any values in local storage. What am I doing wrong? Why is 'foo' not populated on the pages sedond load?

 <script src="http://ajax.googleapis./ajax/libs/jquery/1.4.2/jquery.min.js</script>

<script>
$(document).ready(function() {

if (!localStorage) {return false; }

var foo = localStorage.getItem("key1");

if (foo != null)
{
   document.getByName("identifier").value = foo;
}

localStorage["key1"] = "value1";

});
</script>
Share Improve this question asked Jul 27, 2011 at 16:37 SemsSems 111 silver badge2 bronze badges 1
  • You sure it's not breaking or something? That code ought to work. Did you check in Firebug to see what the localStorage contents are? – Nathan Bubna Commented Jul 29, 2011 at 15:01
Add a ment  | 

4 Answers 4

Reset to default 3

You should use localStorage.setItem. For example

localStorage.setItem("key1", "value1");

NOTE: IE 7 does not have localStorage support

I've also had this same issue. I've discovered that I am unable to retrieve items from local storage during the document.ready, but I am able to get the items afterwards.

I believe you need to use the "setItem" method, i.e.:

localStorage.setItem('key1', 'value1');

Have a look at my code

You do not need getItem and setItem

jQuery('.close-intro').click(function() {
    window.localStorage['intro'] = 1;
    jQuery('.intro-holder').slideUp();
    jQuery('.open-intro').show();
});
jQuery('.open-intro').click(function() {
    window.localStorage['intro'] = 0;
    jQuery('.intro-holder').slideDown();
    jQuery(this).hide();
});
var opcl = window.localStorage['intro'];
if (opcl == 1) {
    jQuery('.intro-holder').slideUp();
    jQuery('.open-intro').show();
}
if (opcl == 0) {
    jQuery('.intro-holder').slideDown();
    jQuery('.open-intro').hide();
}

本文标签: javascriptHTML5 local storage not saving between page refreshesStack Overflow