写入
调用document中的cookie把 名字、值和生命周期写入cookie文件,path一定要填,表示作用域,哪里的文件可以访问该cookie
function writeCookie(name,value,days) {
var expires = ''
var data = new Date()
data.setTime(data.getTime() + (days*24*60*60*1000))
expires = ";expires=" + data.toUTCString()
document.cookie = name + "=" + value + expires + "; path =/";
}
读取
用2层循环来读取需要的值,第一层循环是遍历cookie,第二层循环是遍历cookie中的字符串。
function readCookie(name) {
var searchName = name + "="
if (document.cookie != "") {
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 "";
}
删除
function eraseCookie(name) {
writeCookie(name,'',-1) //将值写为空,生命周期为-1
}