我正在尝试使用 cookie 在 JavaScript 中创建一个警报,这些 cookie 既可以通过名称向用户打招呼,也可以告诉他们他们在网站上赢得了特定游戏的次数。我的用户问候语工作正常,但我似乎无法让计数器正常工作。它涉及调用由先前函数更改的变量,我认为这就是我的问题所在,但我不知道如何解决这个问题。(变量被称为“cardOnePoints”和“cardTwoPoints”。)谁能帮我解决这个问题或者告诉我是否还有什么我做错了?
function getCookieOne(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function setCookieOne(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
var winnerCount = getCookieOne('gamesWonCount') || 0;
function calculateWinnerCount() {
if (cardOnePoints + cardTwoPoints === 21) {
winnerCount = winnerCount + 1;
setCookieOne("gamesWonCount", winnerCount, 365);
}
}
function checkCookie() {
var username = getCookieOne("username");
if (username != null && username != "") {
alert("Sup " + username + "!!! Woah man, you've won " + winnerCount + " game(s)!!!");
} else {
username = prompt("Please enter your name:", "");
if (username != null && username != "") {
setCookieOne("username", username, 365);
}
}
}
你可以在这里看到我的整个代码:http: //jsfiddle.net/hayleyelisa/9padf/2/