javascript show/hide with memory
i have this show/hide menu. It is possibly this menu make with memory?( I open sub menu, refresh page开发者_开发知识库 and this sub menu stil open. )
<script type="text/javascript">
function change(id){
ID = document.getElementById(id);
if(ID.style.display == "")
ID.style.display = "none";
else
ID.style.display = "";
}
</script>
<div onclick="change(5)" style="cursor: hand">
<a href = "#">+</a>News
</div>
<div style="display: none" id="5">
News1<br/>
News2<br/>
</div>
Short answer: Cookies.
Long answer: I suggest you dont try it unless it is really important. Cookies are quite complicated. However, assuming you only want to store one value, it could be simplified.
Heres two nice functions for setting and reading cookies from Quirksmode, if you must:
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
Then you could do something like:
<script type="text/javascript">
function change(id){
ID = document.getElementById(id);
if(ID.style.display == "")
ID.style.display = "none";
else
ID.style.display = "";
createCookie("id",id,7); /* 1 week */
}
window.onload = function() {
try{change(readCookie("id"));}catch(e){} //rough example
};
</script>
<div onclick="change(5)" style="cursor: hand">
<a href = "#">+</a>News
</div>
<div style="display: none" id="5">
News1<br/>
News2<br/>
</div>
Sure you can, use AJAX to send a call to a PHP page (or whatever language you're using) and have it store a session for that user. Then when the page loads, check those session variables to see if they're open or not and render them to start that way. IMO, the extra coding isn't worth remembering which menus they had open. If certain links are important to that page, they should always be visible. Otherwise it shouldn't matter if they get collapsed on page reload.
you could do this via cookies that you set whenever the user clicks. window.load() would need to read cookies and configure of course
精彩评论