【问题标题】:Local storage not applying to remember the last user input for the class toggle本地存储不适用于记住类切换的最后用户输入
【发布时间】:2019-08-09 09:17:48
【问题描述】:

已保存的本地存储值,但如何使用已保存的本地存储。我尝试创建一个函数 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);
        });  
 }
};

【问题讨论】:

  • 与其问“如何做”的问题,不如向我们展示你的尝试,并就问题所在提出一个具体的问题。
  • sori about it.. 更新到我尝试过的内容
  • 哪个输入?以及你以后将如何使用它?
  • 每次用户点击 .dog,.cat, #abc, #xyz,class/value "red" 将被保存到本地存储.. 所以当他们重新访问时,最后保存的 class/值将被应用
  • @Origami 加了答案,看看吧。

标签: javascript storage local


【解决方案1】:

功能逻辑:

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

  • localStorage 中删除具有red 类状态的项目。

这是更新 JavaScript 代码:

抱歉,我无法使用 SO 的 sn-ps 进行现场演示,因为代码已被沙盒化,无法访问 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>之前。

【讨论】:

  • 再次感谢您。对于所有帮助过的人,我感谢你们。由于脑损伤,我有学习障碍,所以我真的很努力。如果我冒犯了任何人,我很抱歉
  • 随时欢迎您!祝你早日康复,度过愉快的一天。
【解决方案2】:

只需使用以下语法:

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

如果您想改为读取值:

localStorage.getItem('myLocalStorageVariable')

【讨论】:

    猜你喜欢
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-27
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多