本文目录一览:
怎么用JS建立一个cookie?
01 script language="JavaScript" type="text/javascript"
02 !--
03 document.cookie="id=12"; // 创建cookie的键和值
04 document.cookie="user=yx"; // 创建cookie的键和值
05 var strCookie=document.cookie; // 获取该域名下的所有cookie值
06 alert(strCookie); // 显示所有的cookie的键与值
07 //--
08 /script
本文来自CSDN博客,转载请标明出处:
用JS编写cookie传值问题
JS设置cookie:
假设在A页面中要保存变量username的值("jack")到cookie中,key值为name,则相应的JS代码为:
document.cookie="name="+username;
JS读取cookie:
假设cookie中存储的内容为:name=jack;password=123
则在B页面中获取变量username的值的JS代码如下:
var username=document.cookie.split(";")[0].split("=")[1];
用原js写获取本地cookie的方法
get(cookie){
let cookieValue=null;
let cookies=document.cookie.split(';');
for(var i=0;icookies.length;i++){
let cookie=cookies[i].trim();去掉前后的空格
if(cookie.substring(0,name.length+1)==(name+'=')){
cookieValue=decodeURICompoent(cookie.substring(name.length+1));
break
}
}
return cookieValue;
}、
js操作cookie
//网页引用
script language="javascript"src="./js/cookie.js"/script
//取cookie值
var hrckdeptcode = Cookie("hrckdeptcode");
var hrckdeptname = Cookie("hrckdeptname");
//保存cookie值
setCookie("hrckdeptcode", deptcode, expdate, "/", null, false);
setCookie("hrckdeptname", deptname, expdate, "/", null, false);
把下面的脚本放到 cookie.js 文件里
var expdate= new Date();
function getCookieVal (offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1) endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
function Cookie (name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg) return getCookieVal (j);
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function setCookie (name,value,expires,path,domain,secure) {
expdate.setTime(expdate.getTime() + (24*60*60*1000*365));
document.cookie = name + "=" + escape (value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
function deleteCookie(name) {
expdate = new Date();
expdate.setTime(expdate.getTime() - (86400 * 1000 * 1));
setCookie(name, "", expdate);
}
用JS编写Cookies保存用户名和密码代码
//创建cookie
function createCookie(name,value,days)
{
if (days)
{
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
//读取cookie值
function readCookie(name)
{
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i ca.length;i++)
{
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
//清空cookie
function eraseCookie(name)
{
createCookie(name,"",-1);
}