我正在尝试使用JavaScript来创建和删除Cookie。我设置它的方式是,当用户点击接受按钮时,我创建一个cookie。如果他们点击拒绝按钮我将其删除。
但是我发现每次尝试删除cookie时它仍然存在。有人能告诉我我做错了吗?
创建COOKIE:
//Create Cookie
function createCookie(name, value, expires, path, domain) {
var cookie = name + "=" + escape(value) + ";";
if (expires) {
// If it's a date
if(expires instanceof Date) {
// If it isn't a valid date
if (isNaN(expires.getTime()))
expires = new Date();
}
else
expires = new Date(new Date().getTime() + parseInt(expires) * 1000 * 60 * 60 * 24);
cookie += "expires=" + expires.toGMTString() + ";";
}
if (path)
cookie += "path=" + path + ";";
if (domain)
cookie += "domain=" + domain + ";";
document.cookie = cookie;
}
//Delete Cookie
function deleteCookie(name, path, domain) {
console.log('deleting ' + name + ' cookie...');
createCookie(name, "", -1, path, domain);
}
//Accept Button Click - CREATE COOKIE
$('#accept').click(function(e){
e.preventDefault();
console.log("You've accept our cookie policy!")
createCookie("MyCookie", "Yummy", 2, "/", ".xyz.com");
});
//Decline Button Click - DELETE COOKIE
$('#decline').click(function(e){
e.preventDefault();
console.log("You've declined our cookie policy!");
deleteCookie("myCookie", "/", ".xyz.com");
});
答案 0 :(得分:0)
为了删除Cookie集,过期日期为过去的某些内容。
您的代码是正确的,只需在过期值中传递任何过期日期。