在w3school上看到这么一段介绍js创建cookies的代码,自己不是很理解,希望与大家分享,共同进步!
/*这个函数首先会检查 document.cookie 对象中是否存有 cookie。假如 document.cookie 对象存有某些 cookie,那么会继续检查我们指定的 cookie 是否已储存。
如果找到了我们要的 cookie,就返回值,否则返回空字符串*/
function getCookie(c_name) { if (document.cookie.length>0) { c_start=document.cookie.indexOf(c_name + "=") //indexOf方法返回检索字符串在被检索字符串中首字母的位置,不存在返回-1 if (c_start!=-1) { c_start=c_start + c_name.length+1 c_end=document.cookie.indexOf(";",c_start) if (c_end==-1) c_end=document.cookie.length return unescape(document.cookie.substring(c_start,c_end)) } } return "" } /*这个函数中的参数存有 cookie 的名称、值以及过期天数。 在上面的函数中,我们首先将天数转换为有效的日期,然后,我们将 cookie 名称、值及其过期日期存入 document.cookie 对象*/ function setCookie(c_name,value,expiredays) { var exdate=new Date() exdate.setDate(exdate.getDate()+expiredays) //注意setDate getDate的用法 document.cookie=c_name+ "=" +escape(value)+ //escape是转码函数 ((expiredays==null) ? "" : ";expires="+exdate.toGMTString()) } /*创建一个函数,这个函数的作用是:如果 cookie 已设置,则显示欢迎词,否则显示提示框来要求用户输入名字*/ function checkCookie() { username=getCookie('username') if (username!=null && username!="") {alert('Welcome again '+username+'!')} else { username=prompt('Please enter your name:',"") if (username!=null && username!="") { setCookie('username',username,365) } } } //调用onLoad事件触发函数,给出提示。
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/28274571/viewspace-747196/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/28274571/viewspace-747196/