删除在函数外部工作的cookie,但不在其中时删除

时间:2013-06-12 12:25:37

标签: javascript cookies setcookie

我试图删除cookie并从函数中设置新的cookie(在cookie_approve内部)并且它不起作用但是如果我把它放在函数之外它会删除cookie。

我的意思是:页面上有一个div。用户单击此div内的按钮(onClick事件)。 Cookie将被创建。下次当用户返回(或刷新网站)时,该div不会出现。

这是我的代码:

//create cookie
function createCookie(name, value, days) {
if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (10000 * 24 * 60 * 60 * 1000));
    var expires = "; expires=" + date.toUTCString();
} else var expires = "";
document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}

//read cookie val
function readCookie(name) {
var nameEQ = escape(name) + "=";
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, c.length);
    if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length, c.length));
}
return null;
}

//change cookie date  
function eraseCookie()
{
document.cookie = 'cookie_approve=; expires='+new Date(0).toUTCString() +'; path=/';
}

//hide div after click, create cookie with val=1 for 7 days
function cookie_approve(){
eraseCookie();
createCookie("cookie_approve", 1, 7);

document.getElementById('cookie_show_info').style.display = "none";
}

if(readCookie("cookie_approve") == undefined){
createCookie("cookie_approve", 0, 7);
}

function show_cookie(){
    document.getElementById('cookies_rules').style.display = "block";
}

function hide_cookie(){
document.getElementById('cookies_rules').style.display = "none";
}

document.write('<div id="cookie_show_info" style="display: none;">Text <div id="cookies_rules">Cookie rules</div>    <a onClick="cookie_approve()">Button</a></div>');

if(readCookie("cookie_approve") == 0){
document.getElementById("cookie_show_info").style.display = "block";
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

你的eraseCookie()函数看起来有点奇怪

试试那些:

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

来源:http://www.quirksmode.org/js/cookies.html