javascript - 是否可以将整个元素存储到本地存储中?

标签 javascript local-storage

我知道我问的是最愚蠢的问题,但由于我不熟悉而且我完全是本地存储的初学者,我想看看代码的机制它是如何工作的,因为它应该是这样的。我创建了一个 div 框和两个按钮,我希望能够更改该框的颜色并将其存储在本地存储中,以便刷新后我希望最终得到样式表的背景颜色,即红色。所以这意味着当我刷新页面后更改为蓝色以保持该颜色时。就像我悲伤的那样,我对本地存储及其使用非常陌生。不管怎样,谢谢你给我的帮助,我知道这又是一个愚蠢的问题,但我对此非常感兴趣。我的 JavaScript 代码如下,如您所见:

var red=document.getElementById("red");
var blue=document.getElementById("blue");


var redColor='red';
var blueColor='blue';

localStorage.setItem('RColor',redColor);
localStorage.setItem('BColor',blueColor);


red.onclick=function red(){
   document.getElementById("box").style.backgroundColor=localStorage.getItem('RColor');


};
blue.onclick=function blue(){
    document.getElementById("box").style.backgroundColor=localStorage.getItem('BColor');


} ;

最佳答案

查看下面我的评论。这是一个示例用法。

var redColor = 'red';
var blueColor = 'blue';

// When opening, read the Color value from localStorage. If it not set, then use the default color (say red)
document.getElementById("box").style.backgroundColor = localStorage.getItem('Color') || redColor;

var red = document.getElementById("red");
var blue = document.getElementById("blue");

red.onclick = function red() {
    // Once user click on red button, Change the box background and update localStorage with Color
    localStorage.setItem('Color', redColor);
    document.getElementById("box").style.backgroundColor = redColor;
};

blue.onclick = function blue() {
  // Once user click on blue button, Change the box background and update localStorage with Color
  localStorage.setItem('Color', blueColor);
  document.getElementById("box").style.backgroundColor = blueColor;
};

关于javascript - 是否可以将整个元素存储到本地存储中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59554801/

相关文章:

Objective C 的 Javascript 语法荧光笔

javascript - 仅当 src 发生更改时才运行构建

html - 本地存储在一个 html 文件中,无需访问互联网

javascript - Chromium localStorage 未显示在开发人员工具中

c# - 使用XML存储数据,如何使用Entity Framework?

javascript - div 内的 div 没有出现?

javascript - 将 jQuery tablesorter 与 thead 结合起来 : How to assign final html output?

javascript - 动画后在 d3.js 中获取 Canvas 位置(cx/cy)以供将来引用?

javascript - 我可以使用什么查询从选定键值的本地存储中获取数据

html - HTML5 LocalStorage 中的自定义对象类?