Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
669 views
in Technique[技术] by (71.8m points)

javascript - Keeping JS changes on DOM after refresh

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the following syntax:

Save data:

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

Retrieve data:

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

More info and examples: https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...