A-A+

JQUERY.COOKIE插件的基本用法

2016年01月12日 前端设计 暂无评论 阅读 5 views 次

JQUERY.COOKIE是一个集成了js的cookie操作的一个插件了,此插件使用简单并且可以达到对cookie读写删除操作,下文为各位深入的介绍。

jQuery.cookie的基本用法:

  1. Include script after the jQuery library (unless you are packaging scripts somehow else):  
  2. <script src="/path/to/jquery.cookie.js"></script>  
  3. Create session cookie:  
  4. $.cookie('name', 'value');  
  5.   
  6. Create expiring cookie, 7 days from then:  
  7.   
  8. $.cookie('name', 'value', { expires: 7 });  
  9. Create expiring cookie, valid across entire site:  
  10.   
  11. $.cookie('name', 'value', { expires: 7, path: '/' });  
  12. Read cookie:  
  13.   
  14. $.cookie('name'); // => "value"  
  15. $.cookie('nothing'); // => undefined  
  16. Read all available cookies:  
  17. $.cookie(); // => { "name": "value" }  
  18. Delete cookie:  
  19.   
  20. // Returns true when cookie was successfully deleted, otherwise false  
  21. $.removeCookie('name'); // => true  
  22. $.removeCookie('nothing'); // => false  
  23.    
  24. // Need to use the same attributes (path, domain) as what the cookie was written with  
  25. $.cookie('name', 'value', { path: '/' });  
  26. // This won't work!  
  27. $.removeCookie('name'); // => false  
  28. // This will work!  
  29. $.removeCookie('name', { path: '/' }); // => true  

JQUERY的COOKIE实例

jquery的cookie插件可以方便操作cookie,首先引入jquery.cookie.js文件,可以去官网下载。

  1. <script type="text/javascript" src="__STATIC__/common/js/jquery.cookie.js"></script>  

以下使用jquery的cookie实现一个简单的功能,一个公共栏,可以点击展开或者收缩,第一次进入页面默认展开,第二次以后进入页面默认收缩,但是点击也可以展开。

通过jquery的cookie记录是否第一次访问界面:

  1. <script>  
  2.     (function($) {  
  3.         var $trigger = $('.dz_box .dz_title');  
  4.         var $view_cur = $('.dz_title a:first');  
  5.         var $view = $('.dz_box .dz_info');  
  6.         var uid = {$businesser_info['uid']};  
  7.    
  8.         var has_read = $.cookie('gonggao_uid_' + uid);  
  9.    
  10.         if (has_read) {  
  11.             $view.hide();  
  12.             $view_cur.removeClass('wel_down01').addClass('wel_up01');  
  13.         }else{  
  14.             $view_cur.removeClass('wel_up01').addClass('wel_down01');  
  15.             $.cookie('gonggao_uid_' + uid, '1');  
  16.         }  
  17.    
  18.         $trigger.click(function () {  
  19.             if ($view_cur.hasClass('wel_up01')) {  
  20.                 $view.slideDown();  
  21.                 $view_cur.removeClass('wel_up01').addClass('wel_down01');  
  22.             } else {  
  23.                 $view.slideUp();  
  24.                 $view_cur.removeClass('wel_down01').addClass('wel_up01');  
  25.             }  
  26.         });  
  27.     })(jQuery);  
  28. </script>  
标签:

给我留言