使用jQuery创建,读取和擦除cookie

时间:2009-10-21 07:35:47

标签: jquery cookies

  

可能重复:
  How to set/unset cookie with jQuery?

有人帮助我。如何使用jQuery创建,读取和删除一些cookie?

4 个答案:

答案 0 :(得分:339)

使用COOKIE plugin

设置一个cookie

$.cookie("example", "foo"); // Sample 1
$.cookie("example", "foo", { expires: 7 }); // Sample 2
$.cookie("example", "foo", { path: '/admin', expires: 7 }); // Sample 3

获取cookie

alert( $.cookie("example") );

删除cookie

$.removeCookie("example");

答案 1 :(得分:98)

据我所知,没有直接的支持,但你可以使用普通的'javascript:

        // Cookies
        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 readCookie(name) {
            var nameEQ = 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 c.substring(nameEQ.length, c.length);
            }
            return null;
        }

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

答案 2 :(得分:15)

答案 3 :(得分:9)

使用jquery cookie插件,该链接今天正常工作: https://github.com/js-cookie/js-cookie