刷新后在DOM上保持JS更改 [英] Keeping JS changes on DOM after refresh

查看:103
本文介绍了刷新后在DOM上保持JS更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我在我的测试网站上有这个奇怪的事情,我有每个链接(无论是菜单,按钮或任何东西)来显示/隐藏div而不是加载页面。非常基本对吗?除非我刷新页面,否则它将全部恢复到预期的主页。基于我的搜索答案,我想我必须使用本地/会话存储选项。会话听起来更好。

So, I have this weird thing going on in my test site, where I have every "link" (be it menu,button, or anything) to show/hide divs instead of loading pages. Pretty basic right? Except whenever I refresh the page, it all reverts back to the Homepage, which is expected. Based on my search for answers, I think I have to use the local/session storage option. Session sounds better.

所以这是交易。我查看了sessionStorage上的w3schools页面,我了解它是如何工作的,但我不知道如何将它应用到我的页面。基本上,我页面上的每个链接都运行一个隐藏前一个div的函数,并显示一个包含内容的新函数。所以我在想,如果每次触发一个函数,它都会在var上存储一个值,该值将指定该函数作为最后使用的函数。然后以某种方式使用sessionStorage并使其工作,但我无法构建它。有什么帮助吗?

So here's the deal. I looked up the w3schools page on sessionStorage and I get how it works, but I don't undestand how I could apply this to my page. Basically every link on my page runs a function that hides the previous div and shows a new one with the content. So I was thinking if every time a function triggered, it would store a value on a var that would appoint the function as the last used. Then somehow use sessionStorage and make it work, but I can't built it. Any help?

以下是我当前代码的一个简短示例。

Here's a short example of my current code.

EDITED

var state = null;
function show1() {
    state = "home";
    "use strict";
    document.getElementById('snow').style.display = "block";
    document.getElementById('btn').style.display = "none";
}


function ramble() {
    state = "ramble";
    "use strict";
    document.getElementById('ramble').style.display = "block";
    document.getElementById('snow').style.display = "none";
    document.getElementById('tex').style.display = "none";
}

这基本上就是它。点击显示/隐藏。

That's basically it.Onclick show/hide.

推荐答案

您可以使用以下语法:

保存数据:

sessionStorage.setItem('key', 'value');

检索数据:

var data = sessionStorage.getItem('key');

更多信息和示例: https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

localStorage也是如此,但是你已经找到了持久性差异

The same goes with localStorage, but with the persistance differences you already found

这篇关于刷新后在DOM上保持JS更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆