10 08 2009

jQuery 操作Cookie 的函数

bigCat Posted in JavaScript - Comment.isBlank
jQuery.cookie = function(name, value, options) {\r\n    if (typeof value != 'undefined') {\r\n        options = options || {};\r\n        if (value === null) {\r\n            value = '';\r\n            options = $.extend({}, options);\r\n            options.expires = -1;\r\n        }\r\n        var expires = '';\r\n        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {\r\n            var date;\r\n            if (typeof options.expires == 'number') {\r\n                date = new Date();\r\n                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));\r\n            } else {\r\n                date = options.expires;\r\n            }\r\n            expires = '; expires=' + date.toUTCString();\r\n        }\r\n        var path = options.path ? '; path=' + (options.path) : '';\r\n        var domain = options.domain ? '; domain=' + (options.domain) : '';\r\n        var secure = options.secure ? '; secure' : '';\r\n        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');\r\n    } else {\r\n        var cookieValue = null;\r\n        if (document.cookie && document.cookie != '') {\r\n            var cookies = document.cookie.split(';');\r\n            for (var i = 0; i < cookies.length; i++) {\r\n                var cookie = jQuery.trim(cookies[i]);\r\n                if (cookie.substring(0, name.length + 1) == (name + '=')) {\r\n                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n        return cookieValue;\r\n    }\r\n};\r\n\r\n//调用\r\n\r\n
$(document).ready(function() {\r\n$('#wCookies').click(function(){\r\n  $.cookie('name', 'test',{expires: 7});				  \r\n});\r\n$('#rCookies').click(function(){\r\n  var test = $.cookie('name');\r\n  alert (test);\r\n});\r\n$('#dCookies').click(function(){\r\n	$.cookie('name', null);							  \r\n});\r\n});

\r\n

Host: (miao) | Word: Press | Code: HTML5