
在前端开发中,我们经常使用javascript动态地创建和修改html元素(dom)。例如,当用户填写表单并点击提交按钮后,页面上会生成一个新的表格行来显示这些数据。然而,这种动态创建的元素只存在于当前页面的内存中。一旦用户刷新页面、关闭浏览器或导航到其他页面,这些通过javascript生成的dom元素就会随之消失,因为浏览器会重新加载原始的html、css和javascript文件,而不会保留之前运行时动态生成的状态。
为了解决这个问题,我们需要一种机制来“记住”这些动态生成的数据,并在页面重新加载时能够将它们恢复到DOM中。
Web Storage API 提供了一种在客户端存储键值对数据的方法,主要包括 localStorage 和 sessionStorage。它们具有以下特点:
对于需要在页面重载后依然保留的数据,localStorage 是一个理想的选择。我们将利用它来存储用户通过表单提交的数据,并在页面加载时将其取出并重新渲染。
要实现动态生成DOM元素的持久化,我们需要完成以下几个关键步骤:
立即学习“前端免费学习笔记(深入)”;
首先,我们定义一个简单的HTML表单和放置生成表格的容器。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>持久化动态DOM元素教程</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
#party div { margin-bottom: 10px; }
label { display: inline-block; width: 150px; }
input[type="text"] { width: 200px; padding: 5px; }
button { padding: 8px 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="请输入联系电话" required>
</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>我们将编写JavaScript代码来处理表单提交,收集数据,并将其存储为JavaScript对象数组,然后使用 JSON.stringify() 将其转换为字符串存储到 localStorage。
// script.js
const storageKey = "activity_data"; // localStorage 的键名
const publishButton = document.getElementById('publishButton');
const tableContainer = document.getElementById('tableContainer');
/**
* 确保表格存在并返回表格元素。如果不存在,则创建包含表头的表格。
* @returns {HTMLTableElement} 表格元素
*/
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;
}
/**
* 将数据渲染为表格行并添加到DOM。
* @param {Object} data - 包含活动信息的对象。
* @param {HTMLTableElement} table - 要添加行的表格元素。
*/
function renderTableRow(data, table) {
const row = document.createElement('tr');
const fields = [data.nom, data.heure1, data.heure2, data.adresse, data.capacite, data.phone];
fields.forEach(value => {
const td = document.createElement('td');
td.innerHTML = value;
row.appendChild(td);
});
table.appendChild(row);
}
/**
* 从 localStorage 加载数据并渲染到页面。
*/
function loadAndRenderData() {
const storedData = localStorage.getItem(storageKey);
if (storedData) {
const activities = JSON.parse(storedData);
if (activities.length > 0) {
const table = ensureTableExists();
// 清空现有数据行,只保留表头
while (table.rows.length > 1) {
table.deleteRow(1);
}
activities.forEach(activity => {
renderTableRow(activity, table);
});
}
}
}
// 监听发布按钮点击事件
publishButton.addEventListener('click', (event) => {
event.preventDefault(); // 阻止表单默认提交行为
// 获取表单值
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 || !phone || !heure1 || !heure2) {
alert("请填写所有必填项!");
return;
}
// 构造数据对象
const newActivity = { nom, adresse, capacite, phone, heure1, heure2 };
// 从 localStorage 获取现有数据,如果不存在则初始化为空数组
let activities = JSON.parse(localStorage.getItem(storageKey) || '[]');
activities.push(newActivity); // 添加新数据
// 将更新后的数据存回 localStorage
localStorage.setItem(storageKey, JSON.stringify(activities));
// 渲染新行到DOM
const table = ensureTableExists();
renderTableRow(newActivity, table);
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 = "";
});
// 页面加载完成后,从 localStorage 恢复数据并渲染
document.addEventListener('DOMContentLoaded', loadAndRenderData);在上述JavaScript代码中,我们已经在 DOMContentLoaded 事件监听器中调用了 loadAndRenderData() 函数。这个函数负责:
这样,无论页面刷新多少次,只要 localStorage 中有数据,这些数据就会在页面加载时被自动恢复并显示出来。
将上述HTML和JavaScript代码分别保存为 index.html 和 script.js 文件,并在同一目录下。
index.html:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>持久化动态DOM元素教程</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
#party div { margin-bottom: 10px; }
label { display: inline-block; width: 150px; }
input[type="text"] { width: 200px; padding: 5px; }
button { padding: 8px 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="请输入联系电话" required>
</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:
const storageKey = "activity_data"; // localStorage 的键名
const publishButton = document.getElementById('publishButton');
const tableContainer = document.getElementById('tableContainer');
/**
* 确保表格存在并返回表格元素。如果不存在,则创建包含表头的表格。
* @returns {HTMLTableElement} 表格元素
*/
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;
}
/**
* 将数据渲染为表格行并添加到DOM。
* @param {Object} data - 包含活动信息的对象。
* @param {HTMLTableElement} table - 要添加行的表格元素。
*/
function renderTableRow(data, table) {
const row = document.createElement('tr');
const fields = [data.nom, data.heure1, data.heure2, data.adresse, data.capacite, data.phone];
fields.forEach(value => {
const td = document.createElement('td');
td.innerHTML = value;
row.appendChild(td);
});
table.appendChild(row);
}
/**
* 从 localStorage 加载数据并渲染到页面。
*/
function loadAndRenderData() {
const storedData = localStorage.getItem(storageKey);
if (storedData) {
const activities = JSON.parse(storedData);
if (activities.length > 0) {
const table = ensureTableExists();
// 清空现有数据行,只保留表头
while (table.rows.length > 1) { // 保持表头行 (索引0)
table.deleteRow(1);
}
activities.forEach(activity => {
renderTableRow(activity, table);
});
}
}
}
// 监听发布按钮点击事件
publishButton.addEventListener('click', (event) => {
event.preventDefault(); // 阻止表单默认提交行为
// 获取表单值
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 || !phone || !heure1 || !heure2) {
alert("请填写所有必填项!");
return;
}
// 构造数据对象
const newActivity = { nom, adresse,以上就是使用 localStorage 实现前端页面重载后动态生成DOM元素的持久化的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号