[英]Persistent Cookie
document.setbackground.bgcolor.value
certifiably works and stores a hex value (such a "000000" for black. The script also works for changing the color of the background of the page when a new one is selected from a live form that updates the value. document.setbackground.bgcolor.value
可以正常工作并存储一个十六进制值(例如,黑色为“ 000000”。该脚本还可以用于从实时表单中选择新的页面背景颜色来更新页面背景的颜色。值。
My problem is that while my code stores a cookie with my browser, it does not work when I close the browser and reopen. 我的问题是,虽然我的代码在浏览器中存储了cookie,但是当我关闭浏览器并重新打开时,它不起作用。 I want the background to start out as whatever was stored in the cookie. 我希望背景从存储在cookie中的内容开始。 Is there something wrong with my code or with my browser settings? 我的代码或浏览器设置有问题吗?
function setBackground () {
if (document.setbackground.bgcolor.value != "none"){
document.body.bgColor = "#" + document.setbackground.bgcolor.value;
document.cookie = "bgColor=" + document.setbackground.bgcolor.value +
";expires=Wednesday, 02-Mar-2020 12:00:00 GMT;";
}
}
This code is embedded into the following HTML in the setPreference.js file: 此代码嵌入到setPreference.js文件中的以下HTML中:
<html>
<head>
<script src="setPreference.js"></script>
</head>
<body bgcolor="#9999CC">
<center>
<form name="setbackground">
Change background color?
<select name="bgcolor" onchange="setBackground();" size="1">
<option value="none">Select color</option>
<option value="9999CC">Lavender</option>
<option value="999966">Light Brown</option>
<option value="66FFCC">Light Green</option>
<option value="FFFFFF">White</option>
</select>
</center>
</form>
</body>
</html>
When user selects a item from select
you'll set bgColor to its value and create a cookie. 当用户从select
选择一个项目时,您会将bgColor设置为其值并创建一个cookie。
But you also need to load that cookie and set bgColor. 但是,您还需要加载该Cookie并设置bgColor。
You can use something simple like this (append it to your js): 您可以使用类似以下的简单内容(将其附加到您的js中):
// document.cookie - name1=value1; name2=value2; name3=value3
function GetCookie(what)
{
var cookies = document.cookie.split(/; ?/g); // now we have array of name=value pairs
for(var i in cookies)
{
var pair = cookies.split("=", 1);
var name = decodeURIComponent(pair[0]);
var value = decodeURIComponent(pair[1]);
if (name == what)
return value;
}
}
window.onload = function ()
{
var color = GetCookie("bgColor"); // note that in the cookie can be ANY value as it comes from the user. So some condition to validate input wouldnt be bad idea
document.setbackground.bgcolor.value = color;
setBackground();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.