【问题标题】:Array not getting saved in local storage阵列未保存在本地存储中
【发布时间】:2016-05-02 17:29:10
【问题描述】:

我正在尝试保存表单(未验证)详细信息并将它们保存在 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>

【问题讨论】:

  • 据我了解,您想要的不是覆盖新值,而是将它们保存在包含旧条目的数组中,不是吗?
  • 你可以使用garlic.js进行数据持久化。
  • @Darth Batu ..是的...

标签: javascript arrays forms object


【解决方案1】:

您应该使用 client_Array.unshift,而不是 client_Array.push。 push 将项目添加到数组的末尾,而 unshift 将其添加为第一个元素(顺便说一句,它是索引 0,而不是 1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    相关资源
    最近更新 更多