如何使用jQuery设置和取消设置cookie,例如创建一个名为test的cookie并将值设置为1?


当前回答

<script type="text/javascript">
    function setCookie(key, value, expiry) {
        var expires = new Date();
        expires.setTime(expires.getTime() + (expiry * 24 * 60 * 60 * 1000));
        document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
    }

    function getCookie(key) {
        var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
        return keyValue ? keyValue[2] : null;
    }

    function eraseCookie(key) {
        var keyValue = getCookie(key);
        setCookie(key, keyValue, '-1');
    }

</script>

你可以把饼干设置成

setCookie('test','1','1'); //(key,value,expiry in days)

你可以拿饼干

getCookie('test');

最后你可以像这样擦掉这些饼干

eraseCookie('test');

希望能对别人有所帮助:)

编辑:

如果要将cookie设置为所有路径/页/目录,则将path属性设置为cookie

function setCookie(key, value, expiry) {
        var expires = new Date();
        expires.setTime(expires.getTime() + (expiry * 24 * 60 * 60 * 1000));
        document.cookie = key + '=' + value + ';path=/' + ';expires=' + expires.toUTCString();
}

谢谢, 维姬

其他回答

下面是如何使用JavaScript设置cookie:

以下代码摘自https://www.w3schools.com/js/js_cookies.asp

函数setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires=" expires="+ d.toUTCString(); 文件中。cookie = cname + "=" + cvalue + ";"+ expires + ";path=/"; }

现在你可以使用下面的函数获取cookie:

function getCookie(cname) { var 名称 = 别名 + “=”; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(';'); for(var i = 0, i <ca.length, i++) { var c = ca[i]; 而 (c.charAt(0) == ' ') { c = c.子字符串(1); } if (c.indexOf(name) == 0) { 返回 c.substring(name.length, c.length); } } 返回 “”; }

最后,这是检查cookie的方法:

函数checkCookie() { var username = getCookie("username"); If(用户名!= ""){ alert(“欢迎再次光临”+用户名); }其他{ username = prompt("请输入您的姓名:",""); If (username != "" && username != null) { setCookie("username", username, 365); } } }

如果你想删除cookie,只需将expires参数设置为一个经过的日期:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

下面的代码将删除当前域内的所有cookie和所有尾随子域(www.some.sub.domain.com, .some.sub.domain.com, .sub.domain.com等等)。

单行的普通JS版本(不需要jQuery):

document.cookie.replace(/(?<=^|;).+?(?=\=|;|$)/g, name => location.hostname.split('.').reverse().reduce(domain => (domain=domain.replace(/^\.?[^.]+/, ''),document.cookie=`${name}=;max-age=0;path=/;domain=${domain}`,domain), location.hostname));

这是这一行的一个可读版本:

document.cookie.replace(
  /(?<=^|;).+?(?=\=|;|$)/g, 
  name => location.hostname
    .split(/\.(?=[^\.]+\.)/)
    .reduceRight((acc, val, i, arr) => i ? arr[i]='.'+val+acc : (arr[i]='', arr), '')
    .map(domain => document.cookie=`${name}=;max-age=0;path=/;domain=${domain}`)
);

我知道有很多很好的答案。通常,我只需要读取cookie,不希望通过加载额外的库或定义函数来增加开销。

下面是如何在一行javascript中读取cookie。我在Guilherme Rodrigues的博客文章中找到了答案:

('; '+document.cookie).split('; '+key+'=').pop().split(';').shift()

这读取cookie命名为key,漂亮,干净和简单。

与之前的答案相比,我减少了操作的数量,我使用以下方法。

function setCookie(name, value, expiry) {
    let d = new Date();
    d.setTime(d.getTime() + (expiry*86400000));
    document.cookie = name + "=" + value + ";" + "expires=" + d.toUTCString() + ";path=/";
}

function getCookie(name) {
    let cookie = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
    return cookie ? cookie[2] : null;
}

function eatCookie(name) {
    setCookie(name, "", -1);
}
<script type="text/javascript">
    function setCookie(key, value, expiry) {
        var expires = new Date();
        expires.setTime(expires.getTime() + (expiry * 24 * 60 * 60 * 1000));
        document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
    }

    function getCookie(key) {
        var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
        return keyValue ? keyValue[2] : null;
    }

    function eraseCookie(key) {
        var keyValue = getCookie(key);
        setCookie(key, keyValue, '-1');
    }

</script>

你可以把饼干设置成

setCookie('test','1','1'); //(key,value,expiry in days)

你可以拿饼干

getCookie('test');

最后你可以像这样擦掉这些饼干

eraseCookie('test');

希望能对别人有所帮助:)

编辑:

如果要将cookie设置为所有路径/页/目录,则将path属性设置为cookie

function setCookie(key, value, expiry) {
        var expires = new Date();
        expires.setTime(expires.getTime() + (expiry * 24 * 60 * 60 * 1000));
        document.cookie = key + '=' + value + ';path=/' + ';expires=' + expires.toUTCString();
}

谢谢, 维姬