Home  >  Article  >  Backend Development  >  How to use cookie settings to view and delete function example code in js

How to use cookie settings to view and delete function example code in js

怪我咯
怪我咯Original
2017-07-10 11:22:331403browse

This article mainly introduces how to use cookie to set the view and delete functions in JavaScript. The article introduces three commonly used presets for js cookies through example codeFunctionLibrary, friends who need it can refer to

3 commonly used default functions (library) of JS cookie

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script>
function setCookie(name, value, iDay) //iday是多少天后过期
{
 var oDate=new Date();
 oDate.setDate(oDate.getDate()+iDay);
 document.cookie=name+&#39;=&#39;+value+&#39;;expires=&#39;+oDate;
} //黄色的等号其实是添加不是赋值的意思. 重复添加不会覆盖
//设置需要有过期的概念, 不设置会即时过期.
function getCookie(name)
{
 var arr=document.cookie.split(&#39;; &#39;);
 for(var i=0;i<arr.length;i++)
 {
  var arr2=arr[i].split(&#39;=&#39;); 
//cookie的存储形式是 user= zhangsan, =是:的意思,split&#39;=&#39; 切割cookie完成查找功能
  if(arr2[0]==name)
  {
   return arr2[1];
  }
 }
 return &#39;&#39;;
}
function removeCookie(name)
{
 setCookie(name, 1, -1); //设置过期为-1天, 就是删除了cookies, 实际上0也可以.
}
removeCookie(&#39;password&#39;);
alert(document.cookie);
</script>
</head>
<body>
</body>
</html>

Remember user name

Sometimes it is necessary to delete the cookies of the website. It is too troublesome one by one. This can delete all the cookies in batches. Friends who need it can refer to it.

function clearCookie(){ 
var keys=document.cookie.match(/[^ =;]+(?=\=)/g); 
if (keys) { 
for (var i = keys.length; i--;) 
document.cookie=keys[i]+&#39;=0;expires=&#39; + new Date( 0).toUTCString() 
} 
}

The above is the detailed content of How to use cookie settings to view and delete function example code in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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