/** Cookie 读写类 读:Cookie.get(name) 写:Cookie.set(name, value, domain, ttl/*是否持久* /) 删除: Cookie.clear(name) 绑定Cookie变化事件 Cookie.change(function(){}) */ var Cookie = function () { var prevCookie = null; var _user = {}; jQuery(function(){ window.setInterval(function () { if (!prevCookie || prevCookie != document.cookie) { prevCookie = document.cookie; jQuery(Cookie).trigger(‘cookie_change‘, prevCookie); } }, 1000); }); return { change: function(fn){ jQuery(this).bind(‘cookie_change‘, fn); }, clear: function (name , domain) { var date = new Date(); date.setTime(date.getTime() - 24 * 60 * 60 * 1000*10); var cookie = name + "="+Cookie.get(‘show_div‘)+"; expires=" + date.toGMTString() + "; path=/;domain=."+domain; document.cookie = cookie; }, set: function (name, value, domain, ttl) { var value = value ? encodeURIComponent(typeof(value) == ‘string‘ ? value : JSON.stringify(value)) : ""; var expires = ""; if (value === "") { ttl = -1; } if (typeof(ttl) != "undefined") { var date = new Date(); date.setTime(date.getTime() + (ttl * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toGMTString(); } try { if (jQuery.browser.msie && value !== "") { var extra = 56 + (domain||‘‘).length; var cookieByteLen = 0; if (document.cookie) { var cookieArr = document.cookie.split(/;\s*/); cookieByteLen = cookieArr.length * extra + document.cookie.length; } var _302e = Cookie.get(name, false); var _302f = _302e ? _302e.length : 0; if ((cookieByteLen + value.length - _302f) > 4096) { throw ("exceeds 4096 byte limit for cookie"); } } document.cookie = name + "=" + value + expires + "; path=/;" + (domain ? (" domain=." + domain) : ""); return true; } catch(e) { return false; } }, get: function (name, parse) { var cookieArr = document.cookie.split(/;\s*/); for (var i = 0; i < cookieArr.length; ++i) { var bits = cookieArr[i].split("=", 2); if (bits[0] == name) { if (parse) { try { return eval("(" + decodeURIComponent(bits[1]) + ")"); } catch(e) {} } else { return decodeURIComponent(bits[1]); } } } return null; } }; } ();
时间: 2024-11-06 03:18:59