用js实现cookie的读、写、全部删除和删除指定cookie值的删除---源码
//设置cookie的值,以及过期时间 function setCookie(cname,cvalue,exdays){ var d = new Date(); d.setTime(d.getTime()+(exdays*24*60*60*1000)); var expires = "expires="+d.toGMTString(); document.cookie = cname+"="+cvalue+"; "+expires; } //得到cookie的值 function getCookie(cname){ var name = cname + "="; var ca = document.cookie.split(';'); for(var i=0; i<ca.length; i++) { var c = ca[i].trim(); if (c.indexOf(name)==0) { return c.substring(name.length,c.length); } } return ""; } //删除指定cookie的值 function removeCookie(cname){ var name = cname + "="; var ca = document.cookie.split(';'); var cookieStr=""; for(var i=0; i<ca.length; i++) { var c = ca[i].trim(); if (c.indexOf(name)==0) { document.cookie =c + ';expires=' + new Date(0).toUTCString() }else{ cookieStr+=c; cookieStr+=";"; } document.cookie =cookieStr; } } //删除全部的cookie值 function clearCookie(){ var keys=document.cookie.match(/[^ =;]+(?=\=)/g); if (keys) { for (var i = keys.length; i--;) ; document.cookie=keys[i]+'=0;expires=' + new Date( 0).toUTCString() ; } } //对cookie的使用 function checkCookie(){ var user=getCookie("name"); removeCookie("name"); if (user!=""){ alert("欢迎 " + user + " 再次访问"); } else { user = prompt("请输入你的名字:",""); if (user!="" && user!=null){ setCookie("username",user,30); } } }