
在web开发中,我们经常需要根据用户交互(例如表单提交)动态生成或修改页面上的html元素。然而,这些通过javascript在运行时创建的元素,默认情况下在用户刷新页面后会丢失,因为浏览器会重新加载html文档并执行脚本,而之前的动态修改不会被保留。为了解决这一问题,我们需要一种机制来持久化这些数据,即使在页面重载后也能恢复。
Web Storage API 提供了一种在客户端浏览器存储键值对数据的方法,主要包括 localStorage 和 sessionStorage。它们相比传统的 Cookie 具有更大的存储容量(通常为 5-10MB),并且不会随每次HTTP请求发送到服务器,从而提高了性能。
在本教程中,我们将使用 localStorage 来实现数据的持久化。
localStorage 的基本操作:
由于 localStorage 只能存储字符串,当需要存储复杂数据结构(如对象或数组)时,需要使用 JSON.stringify() 将其转换为JSON字符串进行存储,并在读取时使用 JSON.parse() 转换回原来的数据结构。
立即学习“前端免费学习笔记(深入)”;
我们将通过一个表单提交数据并生成表格的例子,演示如何使用 localStorage 来持久化表格内容。
首先,创建一个包含表单和用于显示表格的容器的HTML文件。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>动态内容持久化示例</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
#party div { margin-bottom: 10px; }
label { display: inline-block; width: 150px; }
input[type="text"] { padding: 8px; width: 200px; }
button { padding: 10px 15px; background-color: #007bff; color: white; border: none; cursor: pointer; }
button:hover { background-color: #0056b3; }
table { width: 100%; border-collapse: collapse; margin-top: 20px; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background-color: #f2f2f2; }
</style>
</head>
<body>
<div id="party">
<h1>发布信息</h1>
<div>
<label for="nom">名称:</label>
<input type="text" id="nom" name="nom" placeholder="请输入名称" required>
</div>
<div>
<label for="adresse">地址:</label>
<input type="text" id="adresse" name="adresse" placeholder="请输入地址" required>
</div>
<div>
<label for="capacite">容量:</label>
<input type="text" id="capacite" name="capacite" placeholder="请输入容量" required>
</div>
<div>
<label for="phone">电话 (可选):</label>
<input type="text" id="phone" name="phone" placeholder="请输入电话号码">
</div>
<div>
<label for="heure1">开始时间:</label>
<input type="text" id="heure1" name="heure1" placeholder="例如:10:15" required>
</div>
<div>
<label for="heure2">结束时间:</label>
<input type="text" id="heure2" name="heure2" placeholder="例如:20:15" required>
</div>
<button type="button" id="publishButton">发布</button>
</div>
<div id="tableContainer">
<!-- 动态生成的表格将显示在这里 -->
</div>
<script src="script.js"></script>
</body>
</html>创建 script.js 文件,实现表单数据的收集、localStorage 存储以及动态DOM更新。
我们将定义一个函数来统一处理表格的创建和行的添加,并在页面加载时调用它来恢复数据。
// script.js
const storageKey = "poolPartyData"; // localStorage 的键名
// 获取DOM元素
const publishButton = document.getElementById('publishButton');
const tableContainer = document.getElementById('tableContainer');
// 辅助函数:创建表格(如果不存在)并返回表格元素
function ensureTableExists() {
let table = document.querySelector('#tableContainer table');
if (!table) {
table = document.createElement('table');
tableContainer.appendChild(table);
// 创建表头
const headerRow = document.createElement('tr');
const headers = ["名称", "开始时间", "结束时间", "地址", "容量", "电话"];
headers.forEach(text => {
const th = document.createElement('th');
th.innerHTML = text;
headerRow.appendChild(th);
});
table.appendChild(headerRow);
}
return table;
}
// 辅助函数:根据数据对象创建表格行
function createTableRow(data) {
const row = document.createElement('tr');
row.innerHTML = `
<td>${data.nom}</td>
<td>${data.heure1}</td>
<td>${data.heure2}</td>
<td>${data.adresse}</td>
<td>${data.capacite}</td>
<td>${data.phone}</td>
`;
return row;
}
// 发布按钮点击事件处理
publishButton.addEventListener("click", () => {
// 阻止默认的表单提交行为(如果按钮在form内且type不是button)
// event.preventDefault(); // 对于type="button"的按钮,通常不需要
const nom = document.getElementById("nom").value;
const adresse = document.getElementById("adresse").value;
const capacite = document.getElementById("capacite").value;
const phone = document.getElementById("phone").value;
const heure1 = document.getElementById("heure1").value;
const heure2 = document.getElementById("heure2").value;
// 简单的数据验证
if (nom && adresse && capacite && heure1 && heure2) {
const formData = {
nom,
adresse,
capacite,
phone,
heure1,
heure2
};
// 1. 获取现有数据或初始化空数组
let storedData = JSON.parse(localStorage.getItem(storageKey) || '[]');
storedData.push(formData);
// 2. 将更新后的数据保存到 localStorage
localStorage.setItem(storageKey, JSON.stringify(storedData));
// 3. 更新DOM:创建或获取表格,并添加新行
const table = ensureTableExists();
const newRow = createTableRow(formData);
table.appendChild(newRow);
alert("信息已发布并保存!");
// 清空表单字段
document.getElementById("nom").value = '';
document.getElementById("adresse").value = '';
document.getElementById("capacite").value = '';
document.getElementById("phone").value = '';
document.getElementById("heure1").value = '';
document.getElementById("heure2").value = '';
} else {
alert("请填写所有必填字段!");
}
});
// 页面加载时恢复数据
document.addEventListener('DOMContentLoaded', () => {
const storedData = JSON.parse(localStorage.getItem(storageKey) || '[]');
if (storedData.length > 0) {
const table = ensureTableExists(); // 确保表格存在并有表头
storedData.forEach(data => {
const row = createTableRow(data);
table.appendChild(row);
});
}
});通过以上步骤,每次用户发布信息时,数据不仅会显示在页面上,还会被保存到 localStorage 中。当用户刷新页面时,DOMContentLoaded 事件会触发,从 localStorage 中读取数据并重新构建表格,从而实现了动态内容的持久化。
通过理解和应用 localStorage,开发者可以有效地解决前端动态内容在页面刷新后丢失的问题,为用户提供更流畅、更一致的Web应用体验。
以上就是前端数据持久化:确保动态HTML元素在页面重载后依然存在的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号