
本教程详细介绍了如何为工作日计划器实现数据持久化功能。通过利用浏览器提供的web storage api(具体是local storage),用户在日程表输入框中保存的事件内容,即使在页面刷新后也能保持不变。文章将涵盖数据结构设计、保存与加载数据的javascript实现,并提供完整的代码示例和最佳实践建议,帮助开发者构建稳定可靠的web应用程序。
在现代Web应用开发中,数据持久化是一个常见且重要的需求。对于像工作日计划器这样的工具,用户期望其输入的内容能够在页面刷新或关闭浏览器后依然存在。本文将指导您如何使用Web Storage API中的localStorage来实现这一功能,确保您的日程事件能够被有效地保存和加载。
Web Storage API 提供了一种机制,允许Web应用程序在用户的浏览器中本地存储数据。它有两种主要类型:
对于工作日计划器的数据持久化需求,localStorage是理想的选择。它提供以下基本操作:
由于localStorage只能存储字符串,因此在存储JavaScript对象或数组时,需要使用JSON.stringify()将其转换为JSON字符串;在读取时,则使用JSON.parse()将其转换回JavaScript对象或数组。
为了高效地保存和加载每个时间块的事件内容,我们建议使用一个JavaScript对象作为存储结构,其中键是时间块的唯一标识符(例如,textarea的id),值是用户输入的事件文本。
例如:
{
"8AM": "参加项目启动会议",
"9AM": "处理邮件并规划上午工作",
"10AM": "与团队进行日常站会",
// ... 其他时间块的事件
}这种结构使得我们可以直接通过时间ID快速访问或更新特定时间块的事件,避免了遍历数组的开销。
当用户点击保存按钮时,我们需要获取对应时间块的输入内容,并将其更新到localStorage中。
首先,我们需要从localStorage中读取当前保存的所有事件。如果localStorage中没有数据,则初始化一个空对象。
// 在文档加载完成后执行
$(document).ready(function() {
// 尝试从 localStorage 加载数据
// 如果没有,则初始化为空对象
var scheduleContent = JSON.parse(localStorage.getItem("schedule-items")) || {};
// 保存按钮点击事件处理
$("button.saveBtn").on("click", function() {
var container = $(this).parent(); // 获取父级 .row 元素
var textarea = container.find("textarea.description");
var inputValue = textarea.val().trim(); // 获取输入值并去除首尾空格
var inputId = textarea.attr("id"); // 获取 textarea 的 ID
if (inputId && inputValue !== "") {
// 更新 scheduleContent 对象
scheduleContent[inputId] = inputValue;
// 将更新后的对象保存到 localStorage
localStorage.setItem("schedule-items", JSON.stringify(scheduleContent));
// 可选:添加保存成功提示
alert("事件已保存!");
} else if (inputId && inputValue === "") {
// 如果输入为空,则删除该时间块的事件
delete scheduleContent[inputId];
localStorage.setItem("schedule-items", JSON.stringify(scheduleContent));
alert("事件已清空!");
}
});
// ... 其他逻辑 (如加载数据、时间块着色)
});在上述代码中,我们:
为了实现数据持久化,在页面加载时,我们需要从localStorage中读取已保存的事件,并将其填充到对应的textarea元素中。
// 在文档加载完成后执行
$(document).ready(function() {
// 尝试从 localStorage 加载数据
var scheduleContent = JSON.parse(localStorage.getItem("schedule-items")) || {};
// 遍历所有时间块,填充已保存的数据
$(".time-block").each(function() {
var textarea = $(this).find("textarea.description");
var inputId = textarea.attr("id");
if (inputId && scheduleContent[inputId]) {
textarea.val(scheduleContent[inputId]);
}
});
// ... 其他逻辑 (如保存数据、时间块着色)
});此代码片段应放在$(document).ready()函数内部,紧随scheduleContent的初始化之后。它会遍历页面上所有的.time-block元素,找到其中的textarea,然后根据textarea的id从scheduleContent对象中查找对应的事件内容,并将其设置到textarea的value中。
以下是包含实时时钟、时间块颜色更新以及数据持久化功能的完整JavaScript代码 (script.js):
// 实时时钟显示
const clock = document.getElementById("clock");
setInterval(() => {
const now = moment();
const readable = now.format("dddd, MMMM Do YYYY, h:mm:ss a");
clock.textContent = readable;
// 更新当前日期显示
$("#currentDay").text(now.format("dddd, MMMM Do"));
}, 1000);
$(document).ready(function() {
// 尝试从 localStorage 加载数据,如果不存在则初始化为空对象
var scheduleContent = JSON.parse(localStorage.getItem("schedule-items")) || {};
// 1. 加载已保存的事件到对应的 textarea
$(".time-block").each(function() {
var textarea = $(this).find("textarea.description");
var inputId = textarea.attr("id");
if (inputId && scheduleContent[inputId]) {
textarea.val(scheduleContent[inputId]);
}
});
// 2. 保存按钮点击事件处理
$("button.saveBtn").on("click", function() {
var container = $(this).parent(); // 获取父级 .row 元素
var textarea = container.find("textarea.description");
var inputValue = textarea.val().trim(); // 获取输入值并去除首尾空格
var inputId = textarea.attr("id"); // 获取 textarea 的 ID
if (inputId) {
if (inputValue !== "") {
scheduleContent[inputId] = inputValue;
alert("事件已保存!");
} else {
// 如果输入为空,则删除该时间块的事件
delete scheduleContent[inputId];
alert("事件已清空!");
}
// 将更新后的对象保存到 localStorage
localStorage.setItem("schedule-items", JSON.stringify(scheduleContent));
}
});
// 3. 时间块着色逻辑 (过去、现在、未来)
var currentHour = moment().hour(); // 使用 moment.js 获取当前小时 (0-23)
$(".time-block").each(function() {
var blockHour = parseInt($(this).attr("data-hour")); // 获取时间块的 data-hour 属性
if (blockHour < currentHour) {
$(this).addClass('past').removeClass('present future');
} else if (blockHour === currentHour) {
$(this).addClass('present').removeClass('past future');
} else {
$(this).addClass('future').removeClass('past present');
}
});
});为了使JavaScript能够正确地识别和操作每个时间块,HTML结构需要满足以下条件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous" />
<link href="https://fonts.googleapis.com/css?family=Open+Sans&display=swap" rel="stylesheet" />
<link rel="stylesheet" href="./styles/style.css" />
<title>Work Day Scheduler</title>
</head>
<body>
<header class="jumbotron">
<h1 class="display-3">Work Day Scheduler</h1>
<p class="lead">A simple calendar app for scheduling your work day</p>
<p id="currentDay" class="lead"></p>
<div id="clock"></div>
</header>
<div class="container">
<!-- Timeblocks go here -->
<div id ="hour-8" data-hour="8" class = "row time-block">
<div class="col-1 hour">8AM</div>
<textarea id ="8AM" class="col-md-10 description"></textarea>
<button class="col-1 saveBtn btn"><i class="fas fa-save"></i></button>
</div>
<div id ="hour-9" data-hour="9" class = "row time-block">
<div class="col-md-1 hour">9AM</div>
<textarea id="9AM" class="col-md-10 description"></textarea>
<button class="col-1 saveBtn btn"><i class="fas fa-save"></i></button>
</div>
<!-- 更多时间块... -->
<div id ="hour-17" data-hour="17" class = "row time-block">
<div class="col-md-1 hour">5PM</div>
<textarea id="5PM" class="col-md-10 description"></textarea>
<button class="col-1 saveBtn btn"><i class="fas fa-save"></i></button>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="./script.js"></script>
</body>
</html>CSS主要负责界面的布局和视觉效果,与数据持久化逻辑本身无关。以下是示例CSS代码,用于设置时间块的样式和根据时间着色。
body {
font-family: 'Open Sans', sans-serif;
font-size: 16px;
line-height: 1;
}
textarea {
background: transparent;
border: none;
resize: none;
color: #000000;
border-left: 1px solid black;
padding: 10px;
}
.jumbotron {
text-align: center;
background-color: transparent;
color: black;
border-radius: 0;
border-bottom: 10px solid black;
}
.description {
white-space: pre-wrap;
}
.time-block {
text-align: center;
border-radius: 15px;
}
.row {
white-space: pre-wrap;
height: 80px;
border-top: 1px solid white;
}
.hour {
background-color: #ffffff;
color: #000000;
border-top: 1px dashed #000000;
}
.past {
background-color: #d3d3d3;
color: white;
}
.present {
background-color: #ff6961;
color: white;
}
.future {
background-color: #77dd77;
color: white;
}
.saveBtn {
border-left: 1px solid black;
border-top-right-radius: 15px;
border-bottom-right-radius: 15px;
background-color: #06aed5;
color: white;
}
.saveBtn i:hover {
font-size: 20px;
transition: all 0.3s ease-in-out;
}try {
var scheduleContent = JSON.parse(localStorage.getItem("schedule-items")) || {};
} catch (e) {
console.error("解析 localStorage 数据失败:", e);
var scheduleContent = {}; // 出现错误时,初始化为空对象
}通过本教程,您应该已经掌握了如何利用localStorage为工作日计划器实现数据持久化。关键在于合理设计数据结构,并在页面加载时从localStorage读取数据填充UI,在用户操作(如点击保存按钮)时将数据写入localStorage。遵循这些步骤和最佳实践,可以有效提升Web应用的可用性和用户体验。
以上就是使用Local Storage实现工作日计划器数据持久化教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号