使用 localStorage 保存变量无法正常工作

Saving variables with localStorage does not work correctly

我正在编写一个函数来保存一些时间持久性变量(我没有后端,本练习不需要它),但我注意到第一个变量“easy30”保存它在 html 中并且每次我重新加载页面时仍然可见,而第二个变量“easy60”不会保留。它只在第一次保存它,如果我重新加载页面它就会消失......为什么?我基本上对两个变量做完全相同的事情!

 const easy30 = document.getElementById('easy-30');
 const easy60 = document.getElementById('easy-60');

 function saveScoreAndTime(score, time, difficulty) {
   //EASY 30 SECONDS
   var totalScore30 = localStorage.getItem('score30');

   if (
     totalScore30 === null ||
     (+score > +totalScore30 && +time === 30 && difficulty === 'easy')
   ) {
     localStorage.setItem('score30', score);
     let newEasy30Score = localStorage.getItem('score30');
     easy30.textContent = newEasy30Score;
   }

   //EASY 60 SECONDS
   var totalScore60 = localStorage.getItem('score60');

   if (
     totalScore60 === null ||
     (+score > +totalScore60 && +time === 60 && difficulty === 'easy')
   ) {
     localStorage.setItem('score60', score);
     let newEasy60Score = localStorage.getItem('score60');
     easy60.textContent = newEasy60Score;
   }

 }

所以你的代码有问题。

为什么你得到 HTML 节点而不是值是因为你的目标是 HTML 节点而忘记添加 innerHTML

所以在你的情况下你应该这样做 const easy30 = document.getElementById("easy-30").innerHTML; 获取那个 HTML 节点的值

这里还有一个获取和设置本地存储的例子

const easy30 = document.getElementById("easy-30");
const easy60 = document.getElementById("easy-60");
console.log("easy30", easy30.innerHTML);
console.log("easy60", easy60.innerHTML);

const init = async () => {
  const score30 = await localStorage.getItem("easy30");
  console.log("score30", score30);
  const score60 = await localStorage.getItem("easy60");
  console.log("score30", score60);
};

init();

const setLocalStorage = async (key) => {
  localStorage.setItem(key, 30);
};
setLocalStorage("score30");
setLocalStorage("score60");

这是一个 codesandbox 片段