如何让JavaScript动态创建的HTML元素在页面刷新后保留在DOM中
问题描述
我正在开发一个包含HTML表单的网站,编写的JavaScript逻辑可实现如下效果:完成表单填写后点击「Publier」按钮,会基于表单内填入的信息动态生成对应表格。目前该功能可正常运行,但页面刷新后动态生成的表格会全部消失,如何实现页面刷新后这些表格仍可保留在页面中?
原有实现代码
JavaScript 代码
let button = document.querySelector('button[type="button"]'); button.addEventListener("click", () => { let nom = document.getElementById("nom").value; let adresse = document.getElementById("adresse").value; let capacite = document.getElementById("capacite").value; let phone = document.getElementById("phone").value; let heure1 = document.getElementById("heure1").value; let heure2 = document.getElementById("heure2").value; if (nom !== "" && adresse !== "" && capacite !== "" && phone !== "" && heure1 !== "" && heure2 !== "") { console.log(""); btn.style.display = "block"; party.style.display = "none" let table = document.createElement('table'); document.querySelector('body').appendChild(table); let row_1 = document.createElement('tr'); let heading_1 = document.createElement('th'); heading_1.innerHTML = "Nom de la pool party"; let heading_2 = document.createElement('th'); heading_2.innerHTML = "heure de début"; let heading_3 = document.createElement('th'); heading_3.innerHTML = "heure de fin"; let heading_4 = document.createElement('th'); heading_4.innerHTML = "adresse"; let heading_5 = document.createElement('th'); heading_5.innerHTML = "capacité"; let heading_6 = document.createElement('th'); heading_6.innerHTML = "téléphone"; row_1.appendChild(heading_1); row_1.appendChild(heading_2); row_1.appendChild(heading_3); row_1.appendChild(heading_4); row_1.appendChild(heading_5); row_1.appendChild(heading_6); table.appendChild(row_1); let row_2 = document.createElement('tr'); let row_2_data_1 = document.createElement('td'); row_2_data_1.innerHTML = nom; let row_2_data_2 = document.createElement('td'); row_2_data_2.innerHTML = heure1; let row_2_data_3 = document.createElement('td'); row_2_data_3.innerHTML = heure2; let row_2_data_4 = document.createElement('td'); row_2_data_4.innerHTML = adresse; let row_2_data_5 = document.createElement('td'); row_2_data_5.innerHTML = capacite; let row_2_data_6 = document.createElement('td'); row_2_data_6.innerHTML = phone; row_2.appendChild(row_2_data_1); row_2.appendChild(row_2_data_2); row_2.appendChild(row_2_data_3); row_2.appendChild(row_2_data_4); row_2.appendChild(row_2_data_5); row_2.appendChild(row_2_data_6); table.appendChild(row_2); alert("Formulaire envoyé !") } });
HTML 代码
<div id="party"> <h1>Publication</h1> <div> <label for="nom">Nom de la pool party :</label> <input type="text" id="nom" name="nom" placeholder="nom de la pool party" required> </div> <div> <label for="adresse">Adresse de la pool party :</label> <input type="text" id="adresse" name="adresse" placeholder="adresse de la pool party" required> </div> <div> <label for="capacite">Capacité d'acceuil :</label> <input type="text" id="capacite" name="capacite" placeholder="capacité d'acceuil de la pool party" required> </div> <div> <label for="phone">Numéro de téléphone (facultatif) :</label> <input type="text" id="phone" name="phone" placeholder="numéro de téléphone" required> </div> <div> <label for="heure1">Heure de début :</label> <input type="text" id="heure1" name="heure1" placeholder="10h15" required> </div> <div> <label for="heure2">Heure de fin :</label> <input type="text" id="heure2" name="heure2" placeholder="20h15" required> </div> <button type="button">Publier</button> </div>
解决方案
动态生成的DOM节点存储在页面当前运行内存中,页面刷新时浏览器会重置所有运行时状态、重新加载原始HTML文件,没有持久化存储的动态内容自然会被清空。
使用浏览器原生localStorage做本地持久化存储即可实现刷新不丢失,核心逻辑分三步:
- 抽离公共的表格渲染函数,避免重复编写DOM创建代码
- 每次表单提交验证通过后,将提交的数据追加存入localStorage
- 页面首次加载完成时,读取localStorage中存储的所有历史数据,批量渲染成表格
修改后的完整JavaScript代码如下:
// 本地存储的固定key,避免拼写错误 const STORAGE_KEY = 'pool_party_list'; const submitBtn = document.querySelector('button[type="button"]'); const partyForm = document.getElementById('party'); // 补全原代码未声明的返回按钮元素,可根据实际业务调整id const backBtn = document.getElementById('backBtn'); // 单条数据渲染表格的公共方法 function renderSingleTable(data) { const table = document.createElement('table'); document.body.appendChild(table); const headerRow = document.createElement('tr'); const headers = [ "Nom de la pool party", "heure de début", "heure de fin", "adresse", "capacité", "téléphone" ]; headers.forEach(text => { const th = document.createElement('th'); th.innerHTML = text; headerRow.appendChild(th); }); table.appendChild(headerRow); const dataRow = document.createElement('tr'); const dataList = [data.nom, data.heure1, data.heure2, data.adresse, data.capacite, data.phone]; dataList.forEach(text => { const td = document.createElement('td'); td.innerHTML = text; dataRow.appendChild(td); }); table.appendChild(dataRow); } // 页面加载完成后读取历史数据渲染 document.addEventListener('DOMContentLoaded', () => { const storedData = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]'); if (storedData.length > 0) { backBtn.style.display = "block"; partyForm.style.display = "none"; storedData.forEach(item => renderSingleTable(item)); } }) // 提交按钮逻辑 submitBtn.addEventListener("click", () => { const formValues = { nom: document.getElementById("nom").value.trim(), adresse: document.getElementById("adresse").value.trim(), capacite: document.getElementById("capacite").value.trim(), phone: document.getElementById("phone").value.trim(), heure1: document.getElementById("heure1").value.trim(), heure2: document.getElementById("heure2").value.trim() } // 校验所有字段非空 const isAllFilled = Object.values(formValues).every(val => val !== ""); if (isAllFilled) { backBtn.style.display = "block"; partyForm.style.display = "none" // 新数据存入本地存储 const storedData = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]'); storedData.push(formValues); localStorage.setItem(STORAGE_KEY, JSON.stringify(storedData)); // 渲染当前提交的表格 renderSingleTable(formValues); alert("Formulaire envoyé !") } });
补充说明
- localStorage存储的数据没有过期时间,除非用户手动清除浏览器站点数据,否则会永久保存在用户本地
- localStorage仅支持存储字符串类型,因此存储对象/数组时需要用
JSON.stringify转成字符串,读取时用JSON.parse转回结构化数据 - 如果需要新增清空数据功能,调用
localStorage.removeItem(STORAGE_KEY)移除存储数据,同时移除页面上已渲染的表格节点即可 - HTML部分仅需要在原有表单后补充缺失的返回按钮即可,示例:
<button id="backBtn" style="display: none;">新建派对</button>,给该按钮绑定点击事件即可重新显示表单。
内容的提问来源于stack exchange,提问作者Jérémie Lagache
相关产品推荐
相关产品推荐

