开发者

Multiple storages using localStorage

开发者 https://www.devze.com 2022-12-30 22:11 出处:网络
Is it possible that the same name used can have many different values stored separately and to be shown in a list?

Is it possible that the same name used can have many different values stored separately and to be shown in a list?

E.g.:

function save()
{
    var inputfield = document.getElementById('field').innerHTML;
    localStorage['justified'] = inputfield;
}

<input type="text" id="field" onclick="save();" />

Every开发者_如何学JAVA time someone enters something in the input field, and click on save, the localstorage will only save the value in the same name, however, does this conflict the way storage are saved, like being replaced with the latest input value?

Also, is there any way to prevent clearing the localstorage when clearing the cache?


Actually localStorage 'should' be capable of storing integers, strings and arrays. I have been working on a notepad app using localStorage and save all my data using object literals:

var someData = {
    withvars: "and values",
    init: function() {
        // not sure if this works but it should.
    },
    var1: {
        subvar1: "data",
        subvar2: "data2"
    }
};

Then store it using JSON.stringify():

localStorage.setItem(varName, JSON.stringify(someData));

Then access it later with JSON.parse():

var dataBack = JSON.parse(localStorage.getItem("varName"));

If you always use object literals then you will have less trouble keeping track of how to store and how to retrieve data from localStorage.


No. You can store only one value in a localStorage entry.

There are two ways to store more values behind one keyword:

  1. Use localStorage['justified_0'], localStorage['justified_1'] etcetera.
  2. Store multiple values in an array and convert it to JSON before storing in localStorage['justified'] and convert it back to an array after reading.

Clearing the cache does not clear local storage.


This is something quite easily determined with a very simple test page. You can only store one value per key, and the values are not cleared when the cache is cleared. (I've just tried Firefox so far ...)

You can store a list of values in a single key by writing your own function to do it:

function addToPersistentList(listName, value) {
  var val = localStorage[listName] || [];
  val.push(value);
  localStorage[listName] = val; // THIS DOES NOT WORK
}

edit oops it only supports stored strings; crap. OK well if you have json2 you'd do this:

function addToPersistentList(listName, value) {
  var val = localStorage[listName] ? JSON.parse(localStorage[listName]) : [];
  val.push(value.toString());
  localStorage[listName] = JSON.stringify(val);
}

Of course this causes issues if you want to store dates etc.

0

精彩评论

暂无评论...
验证码 换一张
取 消