要在localStorage中正确存储此信息,您需要执行几个步骤.不过,在我们开始编写代码之前,请注意localStorage(目前)不能保存除字符串之外的任何数据类型.您需要序列化用于存储的数组,然后将其解析回以对其进行修改.
Step 1:
The First code snippet below should only be run if you are not already storing a serialized array in your localStorage session
variable.
To ensure your localStorage is setup properly and storing an array, run the following code snippet first:
var a = [];
a.push(JSON.parse(localStorage.getItem('session')));
localStorage.setItem('session', JSON.stringify(a));
The above code should only be run once and only if you are not already storing an array in your localStorage session
variable. If you are already doing this skip to step 2.
第二步:
修改你的函数如下:
function SaveDataToLocalStorage(data)
{
var a = [];
// Parse the serialized data back into an aray of objects
a = JSON.parse(localStorage.getItem('session')) || [];
// Push the new data (whether it be an object or anything else) onto the array
a.push(data);
// Alert the array value
alert(a); // Should be something like [Object array]
// Re-serialize the array back into a string and store it in localStorage
localStorage.setItem('session', JSON.stringify(a));
}
This should take care of the rest for you. When you parse it out, it will become an array of objects.
Hope this helps.