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


当前回答

下面的代码将删除当前域内的所有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}`)
);

其他回答

<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();
}

谢谢, 维姬

在浏览器中设置cookie的简单示例:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>jquery.cookie Test Suite</title>

        <script src="jquery-1.9.0.min.js"></script>
        <script src="jquery.cookie.js"></script>
        <script src="JSON-js-master/json.js"></script>
        <script src="JSON-js-master/json_parse.js"></script>
        <script>
            $(function() {

               if ($.cookie('cookieStore')) {
                    var data=JSON.parse($.cookie("cookieStore"));
                    $('#name').text(data[0]);
                    $('#address').text(data[1]);
              }

              $('#submit').on('click', function(){

                    var storeData = new Array();
                    storeData[0] = $('#inputName').val();
                    storeData[1] = $('#inputAddress').val();

                    $.cookie("cookieStore", JSON.stringify(storeData));
                    var data=JSON.parse($.cookie("cookieStore"));
                    $('#name').text(data[0]);
                    $('#address').text(data[1]);
              });
            });

       </script>
    </head>
    <body>
            <label for="inputName">Name</label>
            <br /> 
            <input type="text" id="inputName">
            <br />      
            <br /> 
            <label for="inputAddress">Address</label>
            <br /> 
            <input type="text" id="inputAddress">
            <br />      
            <br />   
            <input type="submit" id="submit" value="Submit" />
            <hr>    
            <p id="name"></p>
            <br />      
            <p id="address"></p>
            <br />
            <hr>  
     </body>
</html>

简单的只是复制/粘贴并使用此代码设置您的cookie。

确保不要做这样的事情:

var a = $.cookie("cart").split(",");

然后,如果cookie不存在,调试器将返回一些无用的消息,如“。Cookie不是一个函数”。

总是先声明,然后在检查null后进行拆分。是这样的:

var a = $.cookie("cart");
if (a != null) {
    var aa = a.split(",");

下面是如何使用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}`)
);