以下是jQuery操作cookie插件代码: jQuery.cookie = function(name, value, options) { if (typeof value != ’undefined’) { // name and value given, set cookie options = options || {}; if (value === null) { value = ’’; options.expires = -1; } var expires = ’’; if (options.expires && (typeof options.expires == ’number’ || options.expires.toUTCString)) { var date; if (typeof options.expires == ’number’) { date = new Date(); date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); } else { date = options.expires; } expires = ’; expires=’ + date.toUTCString(); // use expires attribute, max-age is not supported by IE } var path = options.path ? ’; path=’ + options.path : ’’; var domain = options.domain ? ’; domain=’ + options.domain : ’’; var secure = options.secure ? ’; secure’ : ’’; document.cookie = [name, ’=’, encodeURIComponent(value), expires, path, domain, secure].join(’’); } else { // only name given, get cookie var cookieValue = null; if (document.cookie && document.cookie != ’’) { var cookies = document.cookie.split(’;’); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + ’=’)) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } }; |
使用方法
jQuery操作cookie的插件,大概的使用方法如下:
$.cookie(’the_cookie’); //读取Cookie值
$.cookie(’the_cookie’, ’the_value’); //设置cookie的值
$.cookie(’the_cookie’, ’the_value’, {expires: 7, path: ’/’, domain: ’www.viming.com’, secure: true});//新建一个cookie 包括有效期 路径 域名等
$.cookie(’the_cookie’, ’the_value’); //新建cookie
$.cookie(’the_cookie’, null); //删除一个cookie
设置一个名称为weburl,值为www.viming.com的cookie:
$.cookie("weburl", "www.viming.com");
设置一个名称为weburl,值为www.viming.com的cookie,同时设置过期时间(expires属性)为7天:
$.cookie("weburl", "www.viming.com", {expires:7});
设置一个名称为weburl,值为www.viming.com的cookie,设置过期时间(expires属性)为7天,同时设置cookie的path属性为”/admin”
$.cookie("weburl", "www.viming.com", {path:’/admin’, expires:7});
读取名称为weburl的cookie值:
alert($.cookie("weburl"));
删除名称为weburl的cookie:
$.cookie("weburl", null);