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

折纸

保存的本地存储值但如何使用已保存的本地存储使用。我尝试创建一个函数 apply 但该类没有应用

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

功能逻辑:

  • button按下a 时,我们检查它是否具有red类(因为所有元素buttons 和其他divs 将red在某个时候接收该类)。
    • 如果它有那个类,那么它将被切换(它将从所有buttons 和其他divs 中删除),因此localStorage将存储类似“不,元素没有红色类”的内容
    • 如果它没有它,它将被切换(它将被添加到所有buttons 和其他divs),因此localStorage将存储类似“是的元素具有红色类”的内容
    • 基本上,如果不应用如果应用类localStorage将存储'0''1'
  • 现在,当页面刷新时,我们检查localStorage存储red类状态的项目是否存在(不存在null)并且具有值,'1'然后将该类应用于所有元素(buttons 和其他divs)。

  • 卸下固定项目red从类状态localStorage

这是更新JavaScript代码:

对不起大家,因为我无法使用 SO 的片段进行现场演示,localStorage因为代码是沙盒的。

无论如何,这里有一个CodePen演示,说明了所需的功能。

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

上面的代码应该放在</body>.

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章