我有一个来自<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);"/>
答案 0 :(得分:1)
以下是使用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");
答案 1 :(得分:0)
您不能永远存储数据。但是您可以将它们存储在Cookie中。
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";
详细了解JS cookie:-https://www.w3schools.com/js/js_cookies.asp