jQuery如何设置/取消cookie?

  • 回答 (2)
  • 关注 (0)
  • 查看 (57)

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

大叔也犯二大叔也犯二提问于
Ne_biubiubiu这就是世界结束的方式回答于

不需要特别使用jQuery来操作cookie。

QuirksMode(包括转义字符)

function createCookie(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    } else {
        expires = "";
    }
    document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/";
}
function readCookie(name) {
    var nameEQ = encodeURIComponent(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 decodeURIComponent(c.substring(nameEQ.length, c.length));
    }
    return null;
}
function eraseCookie(name) {
    createCookie(name, "", -1);
}
死者是小智回答于

看插件:

https://github.com/carhartl/jquery-cookie

你可以这样做:

$.cookie("test", 1);

删除:

$.removeCookie("test");

另外,要在Cookie上设置一定天数的超时时间(这里是10)

$.cookie("test", 1, { expires : 10 });

如果省略了expires选项,则cookie成为会话cookie,并在浏览器退出时被删除。

涵盖所有选项:

$.cookie("test", 1, {

expires : 10, //expires in 10 days

path : '/', //The value of the path attribute of the cookie

//(default: path of page that created the cookie).

domain : 'jquery.com', //The value of the domain attribute of the cookie

//(default: domain of page that created the cookie).

secure : true //If set to true the secure attribute of the cookie

//will be set and the cookie transmission will

//require a secure protocol (defaults to false).

});

要读回cookie的值:

var cookieValue = $.cookie("test");

如果cookie是在与当前路径不同的路径上创建的,则可能希望指定路径参数:

var cookieValue = $.cookie("test", { path: '/foo' });

扫码关注云+社区

领取腾讯云代金券