我有一个来自<input>
的号码,我想在一个选定的地方保存在一个阵列中。我成功地用splice()
做了,但是当重新加载页面时,保存在数组中的数据会重置。如何“永远”保存这些数据?
这是代码:
<label for="number">Number to Save</label>
<input type="text" name="number" id="number" value=""/>
<input type="button" value="click" onclick="myArr.splice(2, 0, number.value);"/>
这是使用localStorage http://jsfiddle.net/nezir/Hn7jc/147/的简单示例
// Retrieve your data from locaStorage
var saveData = JSON.parse(localStorage.saveData || null) || {};
// Store your data.
function saveStuff(obj) {
saveData.obj = obj;
var myArr = [1,2,3,4,5];
console.log(myArr);
saveData.some_array = myArr;
console.log(saveData.some_array);
saveData.some_array = myArr.splice(2);
localStorage.saveData = JSON.stringify(saveData);
}
// Do something with your data.
function loadStuff() {
return saveData.obj || "default";
}
if (saveData.some_array) alert("You were here: " + saveData.some_array);
saveStuff("Stuff");
您无法永久存储数据。但是你可以将它们存储在cookie中。
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";
阅读更多关于JS cookies的信息: - https://www.w3schools.com/js/js_cookies.asp