我有三个功能,主要是从W3schools教程中复制的。 checkCookie,getCookie和setCookie。
代码正常工作,当我只想存储用户名时,但是当我尝试使用getCookie函数来获取人喜欢的颜色时,事情就出错了。该程序仅用于存储用户名:http://jsfiddle.net/rwowf5j8/25/<工作实例。对于TL; DR到底,因为问题可能很简单,不需要读取代码。
来自小提琴的代码:
<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 title = cname + "=";
var cookie_array = document.cookie.split(';');
for(var i=0; i<cookie_array.length; i++) {
var check = cookie_array[i];
while (check.charAt(0)==' ') check = check.substring(1);
if (check.indexOf(title) != -1) {
return check.substring(title.length, check.length);
}
}
return "";
}
function checkCookie() {
var name=getCookie("name");
if (name != "") {
alert("Welcome again " + name);
} else {
name = prompt("Please enter your name:","");
if (name != null && name != "") {
setCookie("name", name, 30);
}
}
}
function RemoveC() {
document.cookie = "name=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
}
function Customise() {
var elem = document.getElementById("Test");
var name=getCookie("name");
if (name != "") {
elem.innerHTML = "Hi there, " + name;
} else {
elem.innerHTML = "";
}
}
</script>
<body onload="checkCookie(); Customise()">
<button onclick="RemoveC()">Remove Cookie</button>
<p id="Test">
</p>
</body>
我尝试修改代码以存储用户喜欢的颜色。我将setCookie和checkCookie函数更改为以下内容:
function setCookie(cname, ccolour, cvalue, cvalue2, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+ccolour+"="+cvalue2+"; "expires;
}
function checkCookie() {
var name=getCookie("name");
if (name != "") {
alert("Welcome again " + name);
} else {
name = prompt("Please enter your name:","");
var colorC = prompt("Please enter your favourite colour:","");
if (name != null && name != "" && colorC != "" && colorC != null) {
setCookie("name", "colour", name, colorC, 30);
}
}
}
我意识到checkCookie函数的开头存在一个问题,因为它只检查名称是否存在并且不检查颜色是否存在但我现在只是测试。
我还更改了自定义功能以获取颜色并将其提醒给用户
var Fcolour = getCookie("colour");
alert(Fcolour);
以下是未正确存储颜色的新代码的小提琴:http://jsfiddle.net/rwowf5j8/28/
现在,没有任何作用。 checkCookie函数不能完全运行。我怀疑我的分号有问题。我不太了解饼干。你可以存储多个值分为“;”吗?比如,name = test;颜色=试验;东西=测试; EXPDATE .....