【问题标题】:What is the best way to store multiple items in local storage?在本地存储中存储多个项目的最佳方法是什么?
【发布时间】:2021-09-20 20:59:34
【问题描述】:

一个元素没有问题。我需要制作至少 10 个按钮,这样它们就不会相互依赖。也就是说,一些按钮带有隐藏文本,而其他按钮则带有开放文本。

最好的方法是什么让代码看起来不像怪胎?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<style>
#myid { display: none; }
</style>

<button onclick="onclickmyid()">Open</button><br><br><span id="myid">Hidden text</span>

<script>
var myid = document.getElementById('myid');
function onclickmyid() {
  myid.style.display = (myid.style.display == 'block') ? '' : 'block';
  localStorage.setItem('conceal', myid.style.display); 
}
if(localStorage.getItem('conceal') == 'block') { 
  document.getElementById('myid').style.display = 'block';
}
</script>

</body>
</html>

【问题讨论】:

  • 你能试着改写你的问题吗

标签: javascript html local-storage


【解决方案1】:

将您需要的所有持久数据放入数组或对象中,然后将该(单个)数组或对象序列化为单个本地存储键。类似于

const config = localStorage.config
  ? JSON.parse(localStorage.config)
  : defaultConfig; // define defaultConfig earlier
cons saveConfig = () => localStorage.config = JSON.stringify(config);

// then, to save to the config when a change is made:
function onclickmyid() {
  const newShow = myid.style.display === '';
  config.myid = newShow;
  updateUI();
  saveConfig();
}

// and retrieve values on pageload:
const updateUI = () => {
  myid.style.display = config.myid ? 'block' : '';
  // etc for other elements
};
updateUI();

我还强烈建议避免使用内联处理程序,它们现在被普遍认为是非常糟糕的做法 - 尽可能使用 JavaScript 的 addEventListener 正确附加侦听器。

对于其他按钮,只需向config 对象添加更多属性,然后在点击处理程序中切换和访问它们。

【讨论】:

  • 感谢addEventListener的链接,有很详细的说明。但是你的例子对我来说仍然很难。你能举一个两个按钮的小例子吗?
  • 对于其他按钮,只需向config 对象添加更多属性,然后在点击处理程序中切换和访问它们。
猜你喜欢
  • 1970-01-01
  • 2019-02-13
  • 2020-04-28
  • 1970-01-01
  • 2021-02-09
  • 2011-02-27
  • 2015-11-08
  • 2014-10-18
  • 1970-01-01
相关资源
最近更新 更多