Home > Web Front-end > JS Tutorial > JS encapsulated cookie operation function examples (setting, reading, deleting)_javascript skills

JS encapsulated cookie operation function examples (setting, reading, deleting)_javascript skills

WBOY
Release: 2016-05-16 15:31:47
Original
1126 people have browsed it

The example in this article describes the JS encapsulated cookie operation function. Share it with everyone for your reference, the details are as follows:

/*设置cookie*/
function setCookie(name, value, iDay)
{
  var oDate=new Date();
  oDate.setDate(oDate.getDate()+iDay);
  document.cookie=name+'='+value+';expires='+oDate;
};
/*使用方法:setCookie('user', 'simon', 11);*/
/*获取cookie*/
function getCookie(name)
{
  var arr=document.cookie.split('; '); //多个cookie值是以; 分隔的,用split把cookie分割开并赋值给数组
  for(var i=0;i<arr[i].length;i++) //历遍数组
  {
    var arr2=arr[i].split('='); //原来割好的数组是:user=simon,再用split('=')分割成:user simon 这样可以通过arr2[0] arr2[1]来分别获取user和simon 
    if(arr2[0]==name) //如果数组的属性名等于传进来的name
    {
      return arr2[1]; //就返回属性名对应的值
    }
    return ''; //没找到就返回空
  }
};
/*使用方法:getCookie('user')*/
/*删除cookie*/
function removeCookie(name)
{
  setCookie(name, 1, -1); //-1就是告诉系统已经过期,系统就会立刻去删除cookie
};
/*使用方法:removeCookie('user')*/

Copy after login

I hope this article will be helpful to everyone in JavaScript programming.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template