jQuery.cookie的基本用法:
Include script after the jQuery library (unless you are packaging scripts somehow else):
Create session cookie:
$.cookie('name', 'value');
Create expiring cookie, 7 days from then:
$.cookie('name', 'value', { expires: 7 });
Create expiring cookie, valid across entire site:
$.cookie('name', 'value', { expires: 7, path: '/' });
Read cookie:
$.cookie('name'); // => "value"
$.cookie('nothing'); // => undefined
Read all available cookies:
$.cookie(); // => { "name": "value" }
Delete cookie:
// Returns true when cookie was successfully deleted, otherwise false
$.removeCookie('name'); // => true
$.removeCookie('nothing'); // => false
// Need to use the same attributes (path, domain) as what the cookie was written with
$.cookie('name', 'value', { path: '/' });
// This won't work!
$.removeCookie('name'); // => false
// This will work!
$.removeCookie('name', { path: '/' }); // => true
JQUERY的COOKIE实例
jquery的cookie插件可以方便操作cookie,首先引入jquery.cookie.js文件,可以去官网下载。
以下使用jquery的cookie实现一个简单的功能,一个公共栏,可以点击展开或者收缩,第一次进入页面默认展开,第二次以后进入页面默认收缩,但是点击也可以展开。
通过jquery的cookie记录是否第一次访问界面: