Javascript 如何使用cookie保存页面状态?
因此,我的网站上有一个夜间模式功能,下面只是我网站上代码的一个简单示例。我想知道如何保存页面的状态,以便页面刷新后保持暗/亮。我是用饼干做的吗?我以前从未在我的任何网站上实现过cookies,我真的需要一些帮助 下面是HTML,上面有激活脚本的按钮:Javascript 如何使用cookie保存页面状态?,javascript,html,cookies,Javascript,Html,Cookies,因此,我的网站上有一个夜间模式功能,下面只是我网站上代码的一个简单示例。我想知道如何保存页面的状态,以便页面刷新后保持暗/亮。我是用饼干做的吗?我以前从未在我的任何网站上实现过cookies,我真的需要一些帮助 下面是HTML,上面有激活脚本的按钮: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <title>Ryan Simms</titl
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Ryan Simms</title>
</head>
<body>
<script src="scripts/lightSwitch.js"></script> <!-- Loads Script -->
<footer>
<button type="button" id="lightSwitchOff"></button>
<button type="button" id="lightSwitchOn"></button>
</footer> <!-- Closes Footer -->
</body>
</html>
设置cookies:
document.cookie = "cookieName=cookieValue";
您还可以指定cookie应该属于的路径。默认为当前页面
documenet.cookie = "cookieName=cookieValue; path=/folder/";
阅读cookies:
var cookies = document.cookie;
这将cookies
的值设置为一个长字符串,其排列方式如下:
"cookie1=value1;cookie2=value2"
请注意,您无法从其他站点访问cookie,document.cookie将仅返回当前域的cookie
有一个很好的cookie教程
下面是一个如何进行解析的示例:
var sugar = document.cookie;
// finds the lights cookie
var start = sugar.indexOf("lights=");
// if there is a light cookie
if (start != -1) {
// moves the start index to the value of the cookie
start += "lights=".length;
// finds the end of the lights cookie value
var end = sugar.indexOf(";", start);
var cookieValue;
// extract the value of the lights cookie
if (end == -1) {
cookieValue = sugar.substring(start);
} else {
cookieValue = sugar.substring(start, end);
}
if (cookieValue == "on") {
lightsOn();
} else {
lightsOff();
}
}
我仍然有点困惑我的例子是什么?在你的
lightsOn()
函数中,你会设置一个cookie,比如:document.cookie=“lights=on”
并在handleDocumentLoad()
函数中解析document.cookie
字符串,查看它是否包含值为“开”的cookie“lights”。如果是这样,您将调用lightsOn()
函数。好的,我在我的lights on函数和lights off函数中添加了一个cookie,但是我不知道如何解析它们来检查它们包含什么,然后如果它们包含on或off,我该怎么办?我真的很困惑,对不起,我是新来的cookies@Ryan用一个例子更新答案。好吧,我这样做了,但当我刷新页面时,它仍然会恢复正常
var sugar = document.cookie;
// finds the lights cookie
var start = sugar.indexOf("lights=");
// if there is a light cookie
if (start != -1) {
// moves the start index to the value of the cookie
start += "lights=".length;
// finds the end of the lights cookie value
var end = sugar.indexOf(";", start);
var cookieValue;
// extract the value of the lights cookie
if (end == -1) {
cookieValue = sugar.substring(start);
} else {
cookieValue = sugar.substring(start, end);
}
if (cookieValue == "on") {
lightsOn();
} else {
lightsOff();
}
}