在這個例子中咱們要建立一個存儲訪問者名字的 cookie。當訪問者首次訪問網站時,他們會被要求填寫姓名。名字會存儲於 cookie 中。當訪問者再次訪問網站時,他們就會收到歡迎詞。javascript
首先,咱們會建立一個可在 cookie 變量中存儲訪問者姓名的函數:html
function setCookie(c_name,value,expiredays) { var exdate=new Date() exdate.setDate(exdate.getDate()+expiredays) document.cookie=c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString()) }
上面這個函數中的參數存有 cookie 的名稱、值以及過時天數。java
在上面的函數中,咱們首先將天數轉換爲有效的日期,而後,咱們將 cookie 名稱、值及其過時日期存入 document.cookie 對象。cookie
以後,咱們要建立另外一個函數來檢查是否已設置 cookie:函數
function getCookie(c_name) { if (document.cookie.length>0) { c_start=document.cookie.indexOf(c_name + "=") 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 "" }
上面的函數首先會檢查 document.cookie 對象中是否存有 cookie。假如 document.cookie 對象存有某些 cookie,那麼會繼續檢查咱們指定的 cookie 是否已儲存。若是找到了咱們要的 cookie,就返回值,不然返回空字符串。網站
最後,咱們要建立一個函數,這個函數的做用是:若是 cookie 已設置,則顯示歡迎詞,不然顯示提示框來要求用戶輸入名字。spa
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) } } }
這是全部的代碼:code
<html> <head> <script type="text/javascript"> function getCookie(c_name) { if (document.cookie.length>0) { c_start=document.cookie.indexOf(c_name + "=") 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 "" } function setCookie(c_name,value,expiredays) { var exdate=new Date() exdate.setDate(exdate.getDate()+expiredays) document.cookie=c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString()) } 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) } } } </script> </head> <body onLoad="checkCookie()"> </body> </html>