我正在尝试保存表单(未验证)详细信息并将它们保存在 JAVASCRIPT 的 localStorage 中,我已经这样做了。但是,当我重新加载浏览器并单击“提交”时,应该保存的先前值并未保存在“数组”中,并且空白表单被替换。我知道当我加载浏览器时,数组和对象 (var client_Array = [];var clientObj = {};
) 会再次初始化,但数组不应该保留旧的详细信息(例如在索引 0 中)并将空白或新副本推送到索引 1 中?现在似乎没有发生这种情况。
此外,此代码仅适用于 chrome,不适用于 FF(单击“加载”btn 时不会在控制台中显示详细信息)。
...请帮忙。提前致谢。
<head>
<style>
form {
width:300px;
}
input {
border:1px solid #FF9933;
width:225px;
height:24px;
margin-bottom:7px;
}
textarea {
border:1px solid #FF9933;
width:225px;
height:100px;
}
.fbtn {
width:80px;
margin-top:10px;
float:right;
text-align:center;
color:#FF6600;
font-weight:bold;
}
</style>
</head>
<body>
<form>
<table border="0">
<tr>
<td width="64">Name</td>
<td width="8">:</td>
<td><input type="text" id="inp_name" ></td>
</tr>
<tr>
<td>Email</td>
<td>:</td>
<td><input type="text" id="inp_email" ></td>
</tr>
<tr>
<td>Phone</td>
<td>:</td>
<td><input type="text" id="inp_phone"></td>
</tr>
<tr>
<td>Address</td>
<td>:</td>
<td><textarea id="inp_address"></textarea>
</td>
</tr>
</table>
<input type="button" onClick="sendDet()" class="fbtn" value="Submit">
<br>
<br>
<br>
<input type="button" onClick="loadit()" class="fbtn" value="Load">
<br>
<br>
<input type="reset" class="fbtn" value="reset">
</form>
<script>
var client_Array = [];
var clientObj = {};
function sendDet(){
var clientObj = {
name : document.getElementById('inp_name').value,
email : document.getElementById('inp_email').value,
phone : document.getElementById('inp_phone').value,
address : document.getElementById('inp_address').value
}
client_Array.push(clientObj)
localStorage.setItem("client", JSON.stringify(client_Array))
}
function loadit(){
var show = JSON.parse(localStorage.getItem("client"))
console.log(show)
}
</script>
</body>
最佳答案
您应该使用 client_Array.unshift,而不是 client_Array.push。 push 将项目添加到数组末尾,而 unshift 将其添加为第一个元素(顺便说一句,索引为 0,而不是 1)
关于javascript - 数组未保存在本地存储中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35008969/