javascript - 如何将日期设置/捕获一次到本地存储?
问题描述
如何在不继续更新的情况下将日期(现在)设置为本地存储一次?我想获得一次,仅此而已,但我仍然希望能够使用它,因为还有另一个功能取决于捕获的日期,关键问题是它不断更新如何停止它。
const currentDayChangeNumber = () => {
const now = new Date();
[...document.querySelectorAll('.day-number')].forEach(day => {
day.textContent = formatDayNumber(now);
incrementDayNumber(now);
});
// saving the now value to LS //
localStorage.setItem('date', `${now}`);
}
解决方案
localStorage.getItem
null
当密钥在本地存储中不存在时返回( https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem)。因此,您可以在更新值之前简单地检查该条件。
if (localStorage.getItem('date') === null) {
localStorage.setItem('date', `${now}`);
}
根据应用程序其余部分的设计,您还可以在调用currentDayChangeNumber
.
推荐阅读
- python - Lambda 函数作为一个小函数参数
- terraform - 在 Terraform aws_instance.connection.private_key 和 aws_key_pair.public_key 中使用 S3
- openssl - Emscripten 静态链接到 OpenSSL
- python - 如何从应用程序 django 中调用应用程序端点
- r - UseMethod(“html_table”)中的错误:没有适用于“html_table”的方法应用于“NULL”类的对象
- flutter - 如何在 Flutter 中解码 GS1-128 条码中的 FNC1 码?
- python - 使用来自不同文件pygame的精灵对象类
- reactjs - Reducer 调度 React Redux
- azure - Azure 自定义标记策略,排除资源类型
- node.js - 无法访问 COVID 数据