Window 對象
- 所有瀏覽器都支持 window 對象钳枕。它表示瀏覽器窗口挤庇。
- 所有 JavaScript 全局對象拐格、函數(shù)以及變量均自動(dòng)成為 window 對象的成員吵取。
- 全局變量是 window 對象的屬性。
- 全局函數(shù)是 window 對象的方法聋溜。
- 甚至 HTML DOM 的 document 也是 window 對象的屬性之一
window.document.getElementById("header");
等同于
document.getElementById("header");
JS_cookie
- cookie 是存儲于訪問者的計(jì)算機(jī)中的變量弄息。每當(dāng)同一臺計(jì)算機(jī)通過瀏覽器請求某個(gè)頁面時(shí),就會(huì)發(fā)送這個(gè) cookie勤婚。你可以使用 JavaScript 來創(chuàng)建和取回 cookie 的值摹量。
有關(guān)cookie的例子:
名字 cookie
當(dāng)訪問者首次訪問頁面時(shí),他或她也許會(huì)填寫他/她們的名字馒胆。名字會(huì)存儲于 cookie 中缨称。當(dāng)訪問者再次訪問網(wǎng)站時(shí)祝迂,他們會(huì)收到類似 "Welcome John Doe!" 的歡迎詞睦尽。而名字則是從 cookie 中取回的型雳。
密碼 cookie
當(dāng)訪問者首次訪問頁面時(shí),他或她也許會(huì)填寫他/她們的密碼纠俭。密碼也可被存儲于 cookie 中。當(dāng)他們再次訪問網(wǎng)站時(shí)冤荆,密碼就會(huì)從 cookie 中取回朴则。
日期 cookie
當(dāng)訪問者首次訪問你的網(wǎng)站時(shí)钓简,當(dāng)前的日期可存儲于 cookie 中汹想。當(dāng)他們再次訪問網(wǎng)站時(shí),他們會(huì)收到類似這樣的一條消息:"Your last visit was on Tuesday August 11, 2005!"撤蚊。日期也是從 cookie 中取回的古掏。
創(chuàng)建和存儲 cookie
在這個(gè)例子中我們要?jiǎng)?chuàng)建一個(gè)存儲訪問者名字的 cookie。當(dāng)訪問者首次訪問網(wǎng)站時(shí)侦啸,他們會(huì)被要求填寫姓名槽唾。名字會(huì)存儲于 cookie 中。當(dāng)訪問者再次訪問網(wǎng)站時(shí)匹中,他們就會(huì)收到歡迎詞。
<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>