【问题标题】:Hide and Show elements across multiple pages跨多个页面隐藏和显示元素
【发布时间】:2018-09-29 03:09:52
【问题描述】:

有没有办法跨多个页面保存一个元素的状态?也许使用会话或本地存储?

这样的功能是我想要实现的。但我希望它记住退出和返回页面时显示和隐藏的内容。

<button onclick="myFunction()">Try it</button>

<div id="myDIV">
This is my DIV element.
</div>

<script>
function myFunction() {
    var x = document.getElementById("myDIV");
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}
</script>

【问题讨论】:

  • 是的,使用 localStorage.setItem('display', 'block') 并使用 localStorage.getItem('display')
  • 这样做:localStorage.setItem('display', x.style.display ) 保存状态并在我再次选择按钮时更新,但是在返回页面时,虽然保存了密钥,但 html 中没有定义样式。
  • 而不是保存 x.style.display,var dis; if (x.style.display === "none") { x.style.display = "block"; dis = 'block' } else { x.style.display = "none"; dis ='none' }
  • 使用变量并在 if else 、 setItem 和 getItem 中赋值以查看最后存储的值
  • 我可以看到存储中最后存储的值,并且当我按下按钮时它正在更新。在 html 中,它将样式更改为显示块和不显示。然而,在返回页面时,没有为 html 元素分配样式,因此默认情况下它会再次显示,即使会话存储具有分配给 display 键的值。

标签: javascript jquery local-storage session-storage


【解决方案1】:

要达到预期的效果,请使用以下选项 localStorage 和 onload 功能

  1. 使用 locaStorage.setItem 和 localStorage.getItem 从 localstorage 设置和获取值

  2. 在 body 上使用 onload 函数从本地存储设置显示

function myFunction() {
    var x = document.getElementById("myDIV");
  console.log(x.style.display)
    if (x.style.display === "none") {
      localStorage.setItem('display','block')
        x.style.display = "block";
    } else {
        localStorage.setItem('display','none')
        x.style.display = "none";
    }
  console.log(localStorage)
}

function checkDisplay(){
      var x = document.getElementById("myDIV");
      x.style.display = localStorage.getItem('display');
}
<body onload="checkDisplay()">
<button onclick="myFunction()">Try it</button>

<div id="myDIV">
This is my DIV element.
</div>
  
  <body>

代码示例 - https://codepen.io/nagasai/pen/BxabBz

【讨论】:

  • 我意识到在您的最后评论之后,我没有使用其他功能进行检查,并且默认不显示任何内容。这个答案对我来说非常有效。谢谢。
猜你喜欢
  • 2014-06-10
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 2021-11-21
  • 1970-01-01
  • 2017-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多