首页 > 解决方案 > 如何正确使用本地存储?

问题描述

我正在制作一个将其值保存在多个页面上的变量,并且我正在使用 localstorage 来执行此操作。问题是它不保存变量,也没有给出错误。

在发布此内容之前我尝试过做什么:我在 localstorage 上搜索了 youtube 教程我尝试使用此网站https://www.taniarascia.com/how-to-use-local-storage-with-javascript/ 我搜索了它在stackoverflow上

我找不到这个问题的答案。

变量.js 文件

var mode = "light";

localStorage.setItem('mode', '');

function draw(){
  
  if (document.body.style.backgroundColor == "#181818"){
    mode = "dark";
    console.log(mode);
  }
  
  if (document.body.style.backgroundColor == "#f2f112" || mode == "dark"){
    mode = "dark";
    alert("Error while attempting to change background to dark theme.")
  }


}

index.html 文件

<!DOCTYPE html>
<html>
  <head>
  <title>Home</title>
  </head>
  <body>
  <p><a href="settings.html">Settings</a></p>
    <script type="text/javascript"></script>
    <script src="variables.js"></script>
    <script src="settings.html"></script>
    <script>

    modeselect = localStorage.getItem(mode);

    if (modeselect == "light"){
      console.log("light mode");
      document.body.style.backgroundColor = "#f2f112";
    }
    if (modeselect == "dark"){
      console.log("dark mode");
      document.body.style.backgroundColor = "#f2f112";
    }

  </script>
    </body>
</html>

settings.html 文件

<!DOCTYPE html>
<html>
  <head>
    <title>Settings</title>
  </head>
  <style>
  .button1 {
  background-color: #444444;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
}
  .button2 {
  background-color: #ffffff;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
  }
  body {
    background-color: rgb(156,158,158);
  }
</style>

<body>
<form>
  <input type="button" class="button1" value="Dark mode" onclick="darkmode()">
  <input type="button" class="button2" value="Light mode" style ="color:black;" onclick="lightmode()">
</form>
<p><a href="index.html">Home</a></p>
<script src="variables.js"></script>
<script>
localStorage.getItem('mode');
function darkmode() {
  mode = "dark";
  alert(mode);
  if (mode == "light"){
    alert("error while changing theme");
  }
  if (mode == "dark"){
  alert("successfully changed to dark mode");
  document.body.style.backgroundColor = "#181818";
  }
}
function lightmode() {
  mode = "light";
  alert(mode);
  if (mode == "light"){
    alert("successfully changed to light mode");
    document.body.style.backgroundColor = "#9c9e9e";
  }
  if (mode == "dark"){
    alert("error while changing theme");
  }
}
</script>
</body>
</html>

标签: javascripthtmlcssweb

解决方案


您没有在本地存储中设置值。您设置的本地存储值为空。

使用值为“mode”的“localStorage.setItem”。例子:

localStorage.setItem('mode', mode);

要获得价值,请使用 localStorage.getItem('mode')


推荐阅读