javascript学习指南|javascript写入读取清除cookie函数

更新时间:2020-10-14    来源:php函数    手机版     字体:

【www.bbyears.com--php函数】

cookie是记录访客足迹及留住访客的良好手段之一,但是处理cookie还是挺麻烦的,下面小指分享三个处理cookie的协助函数,你可以保存在类似cookie.js的文件里,然后调用即可使用这三个神奇的函数了。
首先了解一下cookie的结构:cookie是以键值对的形式保存的,即key=value的格式,各个cookie之间一般是以“;”分隔。

writeCookie(name,value,days):写入cookie
name为cookie键名,value为cookie键值,days为天数,可选,不输入则cookie在网页结束后就失效了。
readCookie(name):读取cookie
name为cookie键名,返回cookie键值
eraseCookie(name):清除cookie
name为cookie键名,清除方法为设为空值并有效期为过去-1天。

 代码如下

function writeCookie(name, value, days) {
  // By default, there is no expiration so the cookie is temporary
  var expires = "";

  // Specifying a number of days makes the cookie persistent
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = "; expires=" + date.toGMTString();
  }

  // Set the cookie to the name, value, and expiration date
  document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
  // Find the specified cookie and return its value
  var searchName = name + "=";
  var cookies = document.cookie.split(";");
  for(var i=0; i < cookies.length; i++) {
    var c = cookies[i];
    while (c.charAt(0) == " ")
      c = c.substring(1, c.length);
    if (c.indexOf(searchName) == 0)
      return c.substring(searchName.length, c.length);
  }
  return null;
}

function eraseCookie(name) {
  // Erase the specified cookie
  writeCookie(name, "", -1);
}

另外最好在使用cookie的使用采用if (navigator.cookieEnabled)检测客户端是否支持cookie。

本文来源:http://www.bbyears.com/jiaocheng/104545.html