Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - show display:none div after refresh

Don't know how to put the question title correctly! I have a div that is displayed by button click. The problem is that if user goes to next page(by clicking another button) and then come back to the old page the div is not shown because page is refreshed, so user needs to click the button again to see the div.

Is there any way to keep div displayed after button clicked for first time?

<div id="tableDiv" style="display:none;" >
<table>
   <td>something</td>
</table>
</div>

<input type="button" value="Show" onClick="showTable()"/>

<script type="text/javascript">         
   function showTable() {
       document.getElementById('tableDiv').style.display = "block";
   }                
</script>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can use the html5 webStorage for this:

localStorage does not expire, whereas sessionStorage gets deleted when the browser is closed (usage of both is equivalent). The webStorage is support by all major browsers and IE >= 8

Plain Javascript

function showTable() {
   document.getElementById('tableDiv').style.display = "block";
   localStorage.setItem('show', 'true'); //store state in localStorage
}

And check the state onLoad:

window.onload = function() {
    var show = localStorage.getItem('show');
    if(show === 'true'){
         document.getElementById('tableDiv').style.display = "block";
    }
}

jQuery

function showTable() {
    $('#tableDiv').show();
    localStorage.setItem('show', 'true'); //store state in localStorage
}

$(document).ready(function(){
    var show = localStorage.getItem('show');
    if(show === 'true'){
        $('#tableDiv').show();
    }
});

Demo

P.S. To remove an item from the localStorage use

localStorage.removeItem('show');

Reference

webStorage


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...