您的位置:首页> 日志> 前端技术 正文
DTOP

jQuery 操作Cookie 的函数

chenke | 2011年08月31日 |

>>收藏本文 已有 0条评论

 

  1. jQuery.cookie = function(name, value, options) { 
  2.           if (typeof value != 'undefined') { 
  3.                     options = options || {}; 
  4.                     if (value === null) { 
  5.                               value = ''
  6.                               options = $.extend({}, options); 
  7.                               options.expires = -1; 
  8.                     } 
  9.                     var expires = ''
  10.                     if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { 
  11.                               var date; 
  12.                               if (typeof options.expires == 'number') { 
  13.                                         date = new Date(); 
  14.                                         date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); 
  15.                               } else { 
  16.                                         date = options.expires; 
  17.                               } 
  18.                               expires = '; expires=' + date.toUTCString(); 
  19.                     } 
  20.                     var path = options.path ? '; path=' + (options.path) : ''
  21.                     var domain = options.domain ? '; domain=' + (options.domain) : ''
  22.                     var secure = options.secure ? '; secure' : ''
  23.                     document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); 
  24.           } else { 
  25.                     var cookieValue = null
  26.                     if (document.cookie && document.cookie != '') { 
  27.                               var cookies = document.cookie.split(';'); 
  28.                               for (var i = 0; i < cookies.length; i++) { 
  29.                                         var cookie = jQuery.trim(cookies[i]); 
  30.                                         if (cookie.substring(0, name.length + 1) == (name + '=')) { 
  31.                                                   cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); 
  32.                                                   break
  33.                                         } 
  34.                               } 
  35.                     } 
  36.                     return cookieValue; 
  37.           } 
  38. }; 
  39. 调用方法! 

    
    		
    1. $(document).ready(function() { 
    2. $('#wCookies').click(function(){ 
    3.      $.cookie('name''test',{expires: 7});                          
    4. }); 
    5. $('#rCookies').click(function(){ 
    6.      var test = $.cookie('name'); 
    7.      alert (test); 
    8. }); 
    9. $('#dCookies').click(function(){ 
    10.      $.cookie('name'null);                                         
    11. }); 
    12. });