首页 > 解决方案 > 如何将日期设置/捕获一次到本地存储?

问题描述

如何在不继续更新的情况下将日期(现在)设置为本地存储一次?我想获得一次,仅此而已,但我仍然希望能够使用它,因为还有另一个功能取决于捕获的日期,关键问题是它不断更新如何停止它。

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}`);
}

标签: javascript

解决方案


localStorage.getItemnull当密钥在本地存储中不存在时返回( https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem)。因此,您可以在更新值之前简单地检查该条件。

if (localStorage.getItem('date') === null) {
    localStorage.setItem('date', `${now}`);
}

根据应用程序其余部分的设计,您还可以在调用currentDayChangeNumber.


推荐阅读