cookie封裝函數與使用方法(轉)


函數封裝:

var Cookie = function(name, value, options) {
    // 如果第二個參數存在
    if (typeof value != 'undefined') {
      options = options || {};
      if (value === null) {
        // 設置失效時間
        options.expires = -1;
      }
      var expires = '';
      // 如果存在事件參數項,並且類型為 number,或者具體的時間,那么分別設置事件
      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 : '', // 設置路徑
        domain = options.domain ? '; domain=' + options.domain : '', // 設置域 
        secure = options.secure ? '; secure' : ''; // 設置安全措施,為 true 則直接設置,否則為空
 
      // 把所有字符串信息都存入數組,然后調用 join() 方法轉換為字符串,並寫入 Cookie 信息
      document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); 
    } else { // 如果第二個參數不存在
      var CookieValue = null;
      if (document.cookie && document.cookie != '') {
        var Cookie = document.cookie.split(';');
        for (var i = 0; i < Cookies.length; i++) {
          var Cookie = (Cookie[i] || "").replace( /^\s+|\s+$/g, "");
          if (Cookie.substring(0, name.length + 1) == (name + '=')) {
            CookieValue = decodeURIComponent(Cookie.substring(name.length + 1));
            break;
          }
        }
      }
      return CookieValue;
    }
  };

  寫入cookie信息:

// 簡單寫入一條 Cookie 信息
cookie("user", "baidu");
// 寫入一條 Cookie 信息,並且設置更多選項
cookie("user", "baidu", {
  expires: 10, // 有效期為 10 天
  path: "/", // 整個站點有效
  domain: "www.baidu.com", // 有效域名
  secure: true // 加密數據傳輸
});

  讀取:

cookie("user");

  刪除:

cookie("user", null);

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM