js添加/獲取/刪除cookie操做方法

var cookieMethod = {cookie

// 添加新cookiedom

setCookie: function(cookieName, cookieValue, options) {
  if(typeof options.expires === 'number') {
    var days = options.expires, t = options.expires = new Date();
    t.setTime(+t + days * 864e+5);
  }

  document.cookie = [
    cookieName, '=', escape(cookieValue),
    options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
    options.path ? '; path=' + options.path : '',
    options.domain ? '; domain=' + options.domain : '',
    options.secure ? '; secure' : ''
  ].join('');
},this

// 獲取指定cookie name的值
getCookie: function(cookieName) {
  var reg = new RegExp('(^| )' + cookieName + '=([^;]*)(;|$)');
  var matchArr = document.cookie.match(reg);
  return !matchArr ? null : matchArr[2];
},code

// 檢測指定cookie name是否存在
checkCookie: function(cookieName) {
  var cookieValue = this.getCookie(cookieName);
  return !cookieValue ? false : true;
},blog

// 將指定cookie設定爲過時cookie,使其無效
delCookie: function(cookieName) {
  var cookieValue = this.getCookie(cookieName);
  if(!cookieValue) return;
  var d = new Date();
  d.setTime(d.getTime() - 1);
  document.cookie = cookieName + '=' + cookieValue + ';expires=' + d.toUTCString();
}get

};io

相關文章
相關標籤/搜索