DIV CSS 佈局教程網

分享實用的 jQuery Cookie 操作插件
編輯:JavaScript綜合知識     

在網頁前端,讀寫 Cookie 是相當頻繁的需求。若純用原生 JavaScript 實作,往往得處理一堆相容性細節。本文分享一個好用的 jQuery Cookie 插件,讓操作變得輕鬆簡潔。

插件原始碼

jQuery.cookie = function(name, value, options) {
  if (typeof value != 'undefined') {
    options = options || {};
    if (value === null) {
      value = '';
      options = $.extend({}, options);
      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();
    }
    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 {
    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]);
        if (cookie.substring(0, name.length + 1) == (name + '=')) {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
        }
      }
    }
    return cookieValue;
  }
};

常見用法

1. 設定 Cookie 值:

$.cookie('userid','123');

2. 新建 Cookie 並指定有效期、路徑與網域:

$.cookie('userid', '123', {expires: 7, path: '/', domain: 'jquery.com', secure: true});

若省略後方的參數物件,則以預設設定生效。

3. 刪除 Cookie(將值設為 null):

$.cookie('userid', null);

4. 讀取 Cookie:

var uId= $.cookie('userid');

有了這個插件,你無須自行撰寫繁瑣的相容性程式碼,讀寫 Cookie 變得直覺又省事。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved