我只是尝试用 cookie 制作一个计时器,使按钮只能点击 3 次(我必须用 cookie 来做,因为它会在进程中刷新页面),我制作了这个计时器,但它不起作用。我的页面上没有任何变化。
我通过//发生其他事情
获得的代码由程序执行。
计时器 - (或者至少我认为可以用作计时器):
mailagain.onclick = function () {
if (typeof getCookie("countIt") !== 'undefined') {
if (checkCookie("countIt") > 3) {
// something happens
} else {
//something else happens
var counter = checkCookie("countIt") + 1;
setCookie("countIt", counter, 1)
}
} else {
setCookie("countIt", 1, 1)
}
};
Cookie 功能:
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 + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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(name) {
var value = getCookie("name");
if (value != "") {
return value;
}
}
最佳答案
一些问题:
- 从 cookie 读取值时,请注意它具有字符串数据类型。您需要先将其转换为数字,然后再与另一个数字进行比较或加 1。
- 函数
checkCookie
使用了错误的(硬编码的)cookie 名称,但它甚至不是必需的函数。您可以使用getCookie
完成所有这些操作。
这是一个工作版本:
mailagain.onclick = function () {
// make sure to convert to number (unitary plus), or use 0 when it is not a number:
var counter = (+getCookie("countIt") || 0) + 1;
setCookie("countIt", counter, 1)
if (counter > 3) {
console.log('clicked too many times! (', counter, ')');
} else {
console.log('clicked ' + counter + ' number of times.');
}
};
关于带 cookie 的 javascript 计数器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44046578/