首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何向localStorage JS添加项目?

如何向localStorage JS添加项目?
EN

Stack Overflow用户
提问于 2021-05-17 15:52:16
回答 1查看 61关注 0票数 2

我有一个函数,可以在点击时设置站点的颜色主题,但当我重新加载页面或转到新页面时,它会恢复到默认主题。我的代码中有一行本应从localStorage获取前一个主题并将其应用于新主题,但我认为它不起作用的原因是实际上没有任何代码将该主题保存到存储中。或者在页面重新加载/更改时localStorage重置。无论哪种方式,我都不确定如何修复它。

这是我的代码:

代码语言:javascript
复制
<a class="switch-light-purple color-palette" id="color-palette" onclick="setTheme('theme-light-purple')">
<script>
  // function to set a given theme/color-scheme
  function setTheme(themeName) {
    localStorage.setItem('theme', themeName);
    document.documentElement.className = themeName;
  }

  // Immediately invoked function to set the theme on initial load
  (function () {
    if (localStorage.getItem('theme') === 'theme-light-purple') {
      setTheme('theme-light-purple');
    }
  })();
</script>
</a>

<a class="switch-dark-blue color-palette" id="color-palette" onclick="setTheme('theme-dark-blue')">
<script>
  // function to set a given theme/color-scheme
  function setTheme(themeName) {
    localStorage.setItem('theme', themeName);
    document.documentElement.className = themeName;
  }

  // Immediately invoked function to set the theme on initial load
  (function () {
    if (localStorage.getItem('theme') === 'theme-dark-blue') {
      setTheme('theme-dark-blue');
    }
  })();
</script>
</a>
EN

回答 1

Stack Overflow用户

发布于 2021-05-17 16:14:15

关注点分离:

始终将您的html、css和js保存在各自的文件中,这是不可替代的。

因此,您的index.html应该如下所示(假设index.htmlstyle.cssmain.js都在同一个文件夹中)。

代码语言:javascript
复制
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="parent-container">
      <a data-theme="theme-dark-blue" class="switch-dark-blue color-palette" id="color-palette">Dark Blue </a>
      <a data-theme="theme-light-purple" class="switch-light-purple color-palette" id="color-palette2">Light Purple</a>
    </div>
    <script src="main.js"></script>
  </body>
</html>

您的CSS将位于一个名为style.css的文件中,

还有你的JS

代码语言:javascript
复制
// This waits for the DOM to complete loading
document.addEventListener('DOMContentLoaded', function() {
  // all your code goes inside this.
});

此外,正如@Sebastian Simon在评论中指出的那样,

重复相同id的

在HTML中无效。不推荐使用像onclick这样的内联事件处理程序。它们是一种过时的、难以维护的、不直观的事件注册方式。请始终使用addEventListener。

唯一ID

例如,您可以将其中一个锚标记的id更改为color-palette2,但由于您有许多不同的主题,因此您可以选择更加不言自明的名称。但是,只要您的id是唯一的(每个页面1个唯一的id ),就可以了。

事件侦听器

使用.addEventListener将事件添加到DOM节点。我已经在我分享的代码片段中做到了这一点。一旦你习惯了,这就很容易了。

我还使用了数据属性将主题以更“动态”的方式传递给逻辑。StackOverflow代码片段不支持localStorage,因此我注释掉了这一行。

代码语言:javascript
复制
function setTheme() {
  let theme;
  let savedTheme = localStorage.getItem('theme')
  
  // check if localstorage already has a theme defined
  // if it has, then set theme variable to it
  // otherwise, get the theme from the data-theme attribute
  // of the current anchor tag clicked represented by this.
  theme = savedTheme || this.dataset.theme
  
  let div = document.querySelector('div.parent-container')
  
  // I'm adding this to a div
  // you can add it to the body tag.
  div.classList.add(theme)
  
  
  // this code can be better but the idea is 
  // to remove all other themes and keep only the intended one.
  if (theme === 'theme-dark-blue') {
    div.classList.remove('theme-light-purple')
  } else {
    div.classList.remove('theme-dark-blue')
  }
  
  console.log(`Set theme to ${theme}`)
}

let palettes = document.querySelectorAll('.color-palette')
palettes.forEach(function(p) {
  p.addEventListener('click', setTheme)
})
代码语言:javascript
复制
a {
  cursor: pointer;
  text-decoration: underline;
  color: blue;
}

.switch-light-purple {
  color: purple;
  margin: 0 15px;
}
代码语言:javascript
复制
<div class="parent-container">
  <a data-theme="theme-dark-blue" class="switch-dark-blue color-palette" id="color-palette">Dark Blue </a>

  <a data-theme="theme-light-purple" class="switch-light-purple color-palette" id="color-palette2">Light Purple</a>
</div>

PS:由于StackOverflow不支持localStorage,代码片段将无法工作。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67565833

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档