前端设置、获取、删除cookie

设置cookie

/**
 * [setCookie 设置 cookie]
 * @author	 Leo
 * @param    {[type]}                 name   [变量名,必选]
 * @param    {[type]}                 value  [变量值,必选]
 * @param    {[type]}                 exdays [过期日期,可选]
 */
function setCookie(name, value, exdays) {
  let cookie = name + "=" + value + ";";
  if (exdays) {
    let d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    let expires = "expires=" + d.toGMTString();
    cookie = cookie + ' ' + expires;
  }
  document.cookie = cookie;
}

获取cookie

/**
 * [getCookie 获取 cookie]
 * @author	 Leo
 * @param    {[type]}                 cname [变量名,必选]
 * @return   {[type]}                 [返回值:变量值(字符串)]
 */
function getCookie(cname) {
  let name = cname + "=";
  let cookie = document.cookie.split(';');
  for(let i = 0, len = cookie.length; i < len; i++) {
    let c = cookie[i].trim();
    if (c.indexOf(name) === 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

删除cookie

/**
 * [getCookie 获取 cookie]
 * @author	 Leo
 * @param    {[type]}                 key[变量名,必选]
 */
function clearCookieByKey(key) {
   setCookie(key, "", -1);
 }

你可能感兴趣的:(前端操作cookie,cookie,设置cookie,删除cookie,获取cookie)