<!DOCTYPE html>
<html>
<body>
<input type="text" id="textstorage">
<button name="testbutton" onclick="myFunction()">send</button>
<div id="result"></div>
<script>
function myFunction(){
alert("dasd")
// Check browser support
var inp = document.getElementById("textstorage");
if (typeof(Storage) != "undefined") {
// Store
localStorage.setItem("result", inp.value);
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("result");
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
}
document.getElementById("result").innerHTML = localStorage.getItem("result");
</script>
</body>
</html>
如何使用数组在网页中存储多个值。请帮助我。
注意:如果我输入一个值,它将替换前一个值。我需要像数组一样存储所有值。
最佳答案
LocalStorage 不支持数组,仅支持字符串值。它存储key:value
对。使用 JSON.stringify()
和 JSON.parse()
将数组间接存储在 LocalStorage
对象中。
例如:
var arr = new Array();
arr[0] = "One";
arr[1] = "Two";
arr[2] = "Three";
localStorage["arr"] = JSON.stringify(arr);
var arrStored = JSON.parse(localStorage["arr"]);
关于javascript - 如何使用 HTML 中的本地存储将数据存储在数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31241536/