Multiple repositories using localStorage

Is it possible that the same name can have many different values, stored separately and displayed in a list?

eg:.

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

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

Each time someone enters something into the input field and clicks on save, localstorage will save only one name, however, does it conflict with saving the store, for example, replacing the last input value?

Also, is there a way to prevent the local storage from being cleared while flushing the cache?

+3
source share
3 answers

localStorage "" , . localStorage :

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

JSON.stringify():

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

JSON.parse():

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

, , localStorage.

+7

. , . ( Firefox ...)

, :

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

edit oops, ; . , json2, :

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

, , ..

+1

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

There are two ways to store more values ​​in one keyword:

  • Use localStorage['justified_0'], localStorage['justified_1']etcetera.
  • Store multiple values ​​in an array and convert them to JSON before saving to localStorage['justified']and convert them back to array after reading.

Removing the cache does not clear the local storage.

0
source

Source: https://habr.com/ru/post/1745522/


All Articles