本地存储不适用于记住 class 切换的最后用户输入

Local storage not applying to remember the last user input for the class toggle

保存的本地存储值但是如何使用保存的本地存储。我尝试创建一个应用函数,但 class 没有应用

document.querySelectorAll("#abc, #xyz").forEach(btn => {  
    btn.addEventListener("click", () => {
        const e = document.querySelectorAll(".dog,.cat, #abc, #xyz");
        e.forEach(el => {
            el.classList.toggle("red");
var xyz = document.getElementById("xyz").className;
localStorage.setItem("vovo", xyz);
        });   
    }); 
})

function apply(){
 var xy = localStorage.getItem('vovo');
 if (xy) {
    var single = document.querySelectorAll(".dog,.cat, #abc, #xyz");
    single.forEach(el => {
        el.classList.add(xy);
        });  
 }
};

只需使用以下语法:

localStorage.setItem('myLocalStorageVariable', 'myValue');

如果您想改为读取值:

localStorage.getItem('myLocalStorageVariable')

功能逻辑:

  • 当按下 button 时,我们检查它是否有 red class(作为所有元素,buttons 和其他 div s,将在某个时候收到 red class)。
    • 如果它有 class 那么它将被切换(它将从所有 buttons 和其他 divs 中删除)因此 localStorage将存储类似 "No the elements don't have the red class".
    • 的内容
    • 如果没有它,它将被切换(它将被添加到所有 buttons 和其他 divs)因此 localStorage 将存储像 "Yes the elements have the red class".
    • 基本上,如果未应用 class,localStorage 将存储 '0',如果应用 class,则存储 '1'
  • 现在,当页面刷新时,我们检查存储 red class 状态的 localStorage 项目是否存在(不是 null) 并具有 '1' 的值,然后将 class 应用于所有元素(buttons 和其他 divs)。

  • localStorage.

  • 中删除保持 red class' 状态的项目

这是更新 JavaScript 代码:

Sorry for everyone as I can't make a live demo using SO's snippets as the localStorage can't be reached because the code is sandboxed.

Anyway, here's a CodePen demo illustrating the required functionality.

const els = document.querySelectorAll('.dog,.cat, #abc, #xyz');

/** when the page finishes loading **/
document.addEventListener('DOMContentLoaded', () => {
    /** check if the 'red' class was applied **/
    applied = window.localStorage.getItem('class-applied') === '0' ? false:true;
  /** remove "class-applied" item from the localStorage **/
  window.localStorage.removeItem('class-applied');
  /** if the "red" class was applied just apply it on document load **/
  applied && els.forEach(el => el.classList.add('red'));
});

els.forEach(btn => {
  btn.addEventListener('click', () => {
    /** store the "red" class' state : '1' means it is applied, '0' means it isn't apllied **/
    window.localStorage.setItem(
      'class-applied',
      !btn.classList.contains('red') ? '1' : '0'
    );
    els.forEach(el => el.classList.toggle('red'));
  });
});

The above code should be placed just before </body>.