我是JavaScript的新手,我坚持使用我创建的代码来显示cookie用户名和命中数。问题是使用setCookies()函数时cookie值不是更新,但是一次又一次地输出相同的值。请帮我解决。
function setCookie(cname, cvalue, exdays, visits) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
var visit = visits.toString()
document.cookie = cname + "=" + cvalue + "; " + expires + "; visits=" + visit;
}
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");
var visitCount = getCookie("visits");
var visitCountConverted = Number(visitCount);
if (visitCountConverted == "") {
visitCountConverted = 1;
}
else if (visitCountConverted >= 1){
visitCountConverted += 1;
}
if (user != "") {
alert("Cookie: " + user + "\n" + "Visits: " + visitCountConverted);
setCookie("username", user, 365, visitCountConverted);
} else {
user = "TheName"; alert("Cookie: " + user + "\n" + "Visits: " + visitCountConverted); setCookie("username", user, 365, visitCountConverted);
}
}
&#13;
非常感谢。
答案 0 :(得分:1)
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
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");
var visitCount = getCookie("visits");
var visitCountConverted = Number(visitCount);
if (visitCountConverted == "") {
visitCountConverted = 1;
}
else if (visitCountConverted >= 1){
visitCountConverted += 1;
}
if (user == "") {
user = "TheName";
setCookie("username", user, 365);
}
alert("Cookie: " + user + "\n" + "Visits: " + visitCountConverted);
setCookie("visits", visitCountConverted, 365);
}
checkCookie();//make sure to call this method so that cookies get set
你没有设置访问计数器cookie我已经重构了你的代码所以请你去试试