Local storage 3 objects
This question already has an answer here:
No, you can't. localStorage
(and sessionStorage
) can store only key-value pairs, where values can only be strings.
The best you can do is to store plain objects, using some serialization algorhythm. JSON is the most common, so you can use JSON.stringify
to convert an object to a string, an JSON.parse
to convert it back to an object - which will not be the "same" (ie a reference to the same data), but something equivalent.
Which mean that this happens:
var a = {value: 5},
j = JSON.stringify(a);
var b = a,
c = JSON.parse(j);
a.value = 7;
b.value; // 7
c.value; // 5
But this doesn't work with DOM elements anyway. They can't be stored, period. Just like any other object of any class that's not Object
, unless they provide a toJSON
method that reliably convert them to strings, which can eventually be parsed back.
The toJSON
method is internally used by JSON.stringify
to convert objects to strings.
Date
objects provide a toJSON
method, for example. You can convert the strings back using Date.parse
:
var d = new Date(),
j = d.toJSON(); // e.g. "2014-02-22T10:35:41.579Z"
var o = new Date(Date.parse(j));
o.getTime() === d.getTime(); // true
o === d; // false
(Keep in mind that JSON isn't natively supported by IE7 and lower.)
You can't do the same for DOM elements, though, so 2 and 3 are not feasible.
Shortly, no. You can only store key/values of the type string.
But, you've to take a look at: Storing Objects in HTML5 localStorage
They explain a workaround by stringify the object.
Quote of CMS(accepted answer):
var testObject = { 'one': 1, 'two': 2, 'three': 3 };
// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
console.log('retrievedObject: ', JSON.parse(retrievedObject));
链接地址: http://www.djcxy.com/p/27940.html
上一篇: 如何在localStorage API HTML5中保存功能
下一篇: 本地存储3个对象