我想在我的網站上創建一個側欄,其工作原理類似於「當第一次登錄用戶進入頁面時,側邊欄將在頁面上,並且一旦他點擊切換按鈕(用於隱藏和顯示側邊欄)如何製作基於cookie的邊欄
它會隱藏和cookie將存儲該操作,刷新頁面側邊欄後將不會在該頁面上,如果他想看到他可以點擊按鈕」。
我想在我的網站上創建一個側欄,其工作原理類似於「當第一次登錄用戶進入頁面時,側邊欄將在頁面上,並且一旦他點擊切換按鈕(用於隱藏和顯示側邊欄)如何製作基於cookie的邊欄
它會隱藏和cookie將存儲該操作,刷新頁面側邊欄後將不會在該頁面上,如果他想看到他可以點擊按鈕」。
更好的辦法是使用localStorage的對這種事情,基本上這裏是如何設置和獲取數據
localStorage.setItem('sidebar', 1); //sets value
localStorage.getItem('sidebar'); //gets value
localStorage.removeItem('sidebar'); //removes value
爲什麼好:當餅乾沒有到期日,將盡快刪除瀏覽器是關閉的,所以在側邊欄上設置過期日期切換是非常愚蠢的事情,最好是使用localStorage,因爲它沒有限制,並使用更好的API。 All major browsers support it。瞭解更多關於localStorage
<!DOCTYPE html>
<html>
<head>
<script>
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname) {
var name = cname + "=";
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);
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user=getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
</script>
</head>
<body onload="checkCookie()">
</body>
</html>
爲了更好的去這個鏈接:
如何設置/ Javascript中得到的cookie:http://stackoverflow.com/questions/4825683/how- do-i-create-and-read-a-value-from-cookie。這應該對你有所幫助。 – Webice