You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用数组将表单数据存储到Local Storage并在新页面读取?

没问题,我来一步步教你实现这个需求——把表单数据用数组存在Local Storage里,再在新页面读取展示。

第一步:表单页面收集数据并存储到Local Storage

首先,我们需要给表单添加提交事件监听,阻止默认的表单跳转行为,然后把用户输入的字段值整理成对象,再加入到数组中(这样可以保存多条表单记录),最后把数组转成JSON字符串存入Local Storage(因为Local Storage只能存储字符串类型的数据)。

我先给你的表单补上提交按钮,然后加上处理逻辑:

<form id="myform">
  <label for="fname" class="fname_label">Name</label>
  <input type="text" id="fname" class="input1" placeholder="Full Name" name="fname" required>
  
  <label for="phone">Phone</label>
  <input type="number" name="phone" id="phone" placeholder="Phone Number" required>
  
  <label for="textarea" class="textarea_label">Address:</label>
  <textarea name="address" id="textarea" type="text" required></textarea>
  
  <!-- 添加提交按钮 -->
  <button type="submit">Save & Go to Next Page</button>
</form>

<script>
// 监听表单提交事件
document.getElementById('myform').addEventListener('submit', function(e) {
  // 阻止表单默认提交跳转
  e.preventDefault();
  
  // 收集当前表单的所有输入值
  const newEntry = {
    fullName: document.getElementById('fname').value,
    phoneNumber: document.getElementById('phone').value,
    address: document.getElementById('textarea').value
  };
  
  // 读取Local Storage中已有的数据数组(如果没有就初始化空数组)
  let savedEntries = JSON.parse(localStorage.getItem('formDataArray')) || [];
  
  // 将新的表单数据加入数组
  savedEntries.push(newEntry);
  
  // 把更新后的数组转成JSON字符串,存回Local Storage
  localStorage.setItem('formDataArray', JSON.stringify(savedEntries));
  
  // 提示保存成功,跳转到新页面(替换成你的新页面路径)
  alert('数据已保存!');
  window.location.href = 'your-new-page.html';
});
</script>

关键细节说明:

  • JSON.stringify():把数组/对象转成字符串,因为Local Storage只支持存储字符串。
  • JSON.parse():读取时把字符串转回数组/对象,这样才能正常操作数据。
  • || []:处理首次存储的情况——如果Local Storage里还没有formDataArray这个键,就默认用空数组,避免报错。
第二步:新页面读取并展示Local Storage中的数据

在新页面中,我们只需要读取Local Storage里的数组,然后循环遍历把数据渲染到页面上即可:

<h2>Saved Form Entries</h2>
<div id="entries-container"></div>

<script>
// 从Local Storage读取数据
const savedEntries = JSON.parse(localStorage.getItem('formDataArray')) || [];
const container = document.getElementById('entries-container');

// 渲染数据到页面
if (savedEntries.length > 0) {
  savedEntries.forEach((entry, index) => {
    const entryCard = document.createElement('div');
    entryCard.style.border = '1px solid #ddd';
    entryCard.style.padding = '15px';
    entryCard.style.margin = '10px 0';
    entryCard.innerHTML = `
      <h3>Entry ${index + 1}</h3>
      <p><strong>Full Name:</strong> ${entry.fullName}</p>
      <p><strong>Phone Number:</strong> ${entry.phoneNumber}</p>
      <p><strong>Address:</strong> ${entry.address}</p>
    `;
    container.appendChild(entryCard);
  });
} else {
  container.innerHTML = '<p>No saved entries found.</p>';
}
</script>

这段代码会检查是否有保存的数据:如果有,就为每条记录创建一个卡片展示;如果没有,就显示提示文字。

内容的提问来源于stack exchange,提问作者Nitin singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:34:26