0

我试图删除 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";
}

感谢帮助。

4

1 回答 1

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

于 2013-06-12T12:49:48.497 回答