实例: 创建一个欢迎cookie

实例: 创建一个欢迎cookie

利用用户在提示框中输入的数据创建一个 JavaScript Cookie,当该用户再次访问该页面时,根据 cookie 中的信息发出欢迎信息

首先,我们会创建一个可在 cookie 变量中存储访问者姓名的函数:

  1: function setCookie(c_name,value,expiredays)
  2: {
  3: var exdate=new Date()
  4: exdate.setDate(exdate.getDate()+expiredays)
  5: document.cookie=c_name+ "=" +escape(value)+
  6: ((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
  7: }

上面这个函数中的参数存有 cookie 的名称、值以及过期天数。

在上面的函数中,我们首先将天数转换为有效的日期,然后,我们将 cookie 名称、值及其过期日期存入 document.cookie 对象。

之后,我们要创建另一个函数来检查是否已设置 cookie:

  1: function getCookie(c_name)
  2: {
  3: if (document.cookie.length>0)
  4:   {
  5:   c_start=document.cookie.indexOf(c_name + "=")
  6:   if (c_start!=-1)
  7:     { 
  8:     c_start=c_start + c_name.length+1 
  9:     c_end=document.cookie.indexOf(";",c_start)
 10:     if (c_end==-1) c_end=document.cookie.length
 11:     return unescape(document.cookie.substring(c_start,c_end))
 12:     } 
 13:   }
 14: return ""
 15: }

上面的函数首先会检查 document.cookie 对象中是否存有 cookie。假如 document.cookie 对象存有某些 cookie,那么会继续检查我们指定的 cookie 是否已储存。如果找到了我们要的 cookie,就返回值,否则返回空字符串。

上面的函数首先会检查 document.cookie 对象中是否存有 cookie。假如 document.cookie 对象存有某些 cookie,那么会继续检查我们指定的 cookie 是否已储存。如果找到了我们要的 cookie,就返回值,否则返回空字符串。

最后,我们要创建一个函数,这个函数的作用是:如果 cookie 已设置,则显示欢迎词,否则显示提示框来要求用户输入名字。

  1: function checkCookie()
  2: {
  3: username=getCookie('username')
  4: if (username!=null && username!="")
  5:   {alert('Welcome again '+username+'!')}
  6: else 
  7:   {
  8:   username=prompt('Please enter your name:',"")
  9:   if (username!=null && username!="")
 10:     {
 11:     setCookie('username',username,365)
 12:     }
 13:   }
 14: }

这是所有的代码:

  1: <html>
  2: <head>
  3: <script type="text/javascript">
  4: function getCookie(c_name)
  5: {
  6: if (document.cookie.length>0)
  7:   {
  8:   c_start=document.cookie.indexOf(c_name + "=")
  9:   if (c_start!=-1)
 10:     { 
 11:     c_start=c_start + c_name.length+1 
 12:     c_end=document.cookie.indexOf(";",c_start)
 13:     if (c_end==-1) c_end=document.cookie.length
 14:     return unescape(document.cookie.substring(c_start,c_end))
 15:     } 
 16:   }
 17: return ""
 18: }
 19: 
 20: function setCookie(c_name,value,expiredays)
 21: {
 22: var exdate=new Date()
 23: exdate.setDate(exdate.getDate()+expiredays)
 24: document.cookie=c_name+ "=" +escape(value)+
 25: ((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
 26: }
 27: 
 28: function checkCookie()
 29: {
 30: username=getCookie('username')
 31: if (username!=null && username!="")
 32:   {alert('Welcome again '+username+'!')}
 33: else 
 34:   {
 35:   username=prompt('Please enter your name:',"")
 36:   if (username!=null && username!="")
 37:     {
 38:     setCookie('username',username,365)
 39:     }
 40:   }
 41: }
 42: </script>
 43: </head>
 44: 
 45: <body onLoad="checkCookie()">
 46: </body>
 47: </html> 
 
Indexof() 的使用
http://www.w3school.com.cn/js/jsref_indexof.asp
posted @ 2013-04-29 22:50  搅着青春吹泡泡  阅读(332)  评论(0)    收藏  举报