1、设置一二级域名共用的cookie:设置domain为一级域名,可一、二级域名共用的cookie
$.cookie(‘f_city‘,‘北京|101010100|,锦州|101070701|‘,{expires: 999, path: ‘/‘,domain: ‘weather.com.cn‘})
2、删除同名不同域的cookie (一个页面中.weather.com.cn域 和 www.weather.com.cn域下,都有f_city这个值,怎么删除其中任一)
$.cookie(‘f_city‘,null,{ path: ‘/‘}) //删除当前域 www.weather.com.cn域下的 f_city $.cookie(‘f_city‘,null,{ path: ‘/‘, domain: ‘weather.com.cn‘}) //删除 .weather.com.cn域下的 f_city
3、读取cookie:$.cookie(‘f_city‘),当读取cookie键值为 f_city 的值时,如果有不同域下的多个f_city,则读取创建最早的f_city值,而与域无关
var cookie_f_city= $.cookie(‘f_city‘); //读取cookie只有一种写法,不接受{domain}参数,也就是说,当有域同名参数时,只读创建最早的 f_city
=======================
下面是jq-cookie这个插件的源码
/** * Cookie plugin * * Copyright (c) 2006 Klaus Hartl (stilbuero.de) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ /** * *1、设置cookie的值,比如我们要设置变量名为userid对应值为123的cookie,代码如下: * $.cookie(‘userid‘,‘123‘); * *2、新建一个cookie,并设置cookie的有效期 路径 域名等,代码如下: * $.cookie(‘userid, ‘123‘, {expires: 7, path: ‘/‘, domain: ‘jquery.com‘, secure: true});注意:如果去掉后面{}的参数,新建后将以默认设置生效。 * *3、删除cookie,即把对应cookie值置为null,代码如下: * $.cookie(‘userid‘, null); * *4、读取cookie,如读取变量名为userid的cookie值,代码如下: * var uId= $.cookie(‘userid‘); * */ /** * Get the value of a cookie with the given name. * * @example $.cookie(‘the_cookie‘); * @desc Get the value of a cookie. * * @param String name The name of the cookie. * @return The value of the cookie. * @type String * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/[email protected] */ 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; } };
var cookie_f_city= $.cookie(‘f_city‘); //读取cookie只有一种写法,不接受{domain}参数,也就是说,当有域同名参数时,只读创建最早的 f_city
时间: 2024-10-29 12:55:08