【发布时间】: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