什么是cookie
- 用來保存頁面信息的具温,如用戶名、密碼
- cookie的特性:同一個網(wǎng)站中所有的頁面共享一套cookie血巍;數(shù)量、大小限制端逼;過期時間
- js中使用cookie:document.cookie
如何設(shè)置cookie朗兵?
在js中,使用document.cookie = "鍵=值"
即可顶滩,但是這種方式設(shè)置的cookie由于沒有添加過期時間矛市,所以關(guān)閉瀏覽器,cookie就丟失诲祸,我們要在后邊繼續(xù)加上expires=時間
設(shè)置上國旗時間即可.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript">
// 獲取系統(tǒng)當(dāng)前時間
var oDate = new Date();
// 設(shè)置距離當(dāng)前時間多少天后cookit過期
oDate.setDate(oDate.getDate() + 30);
// 設(shè)置cookie及過期時間
document.cookie = "userName=hello;expires=" + oDate;
document.cookie = "password=123456;expires=" + oDate;
alert(document.cookie);
</script>
</head>
<body>
</body>
</html>
效果圖:

如何從cookie中取值
示例:將用戶名密碼寫入
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
div {
width: 500px;
height: 500px;
margin: 0 auto;
}
#userName {
display: block;
width: 200px;
height: 30px;
margin: 0 auto;
}
#password {
display: block;
width: 200px;
height: 30px;
margin: 0 auto;
}
#save {
display: block;
width: 100px;
height: 20px;
margin: 0 auto;
}
#cokie {
display: block;
width: 100px;
height: 20px;
margin: 0 auto;
}
</style>
<script type="text/javascript">
window.onload = function () {
var oBtn = document.getElementById('save');
var oBtn1 = document.getElementById('cokie');
var name ;
var pass ;
oBtn.onclick = function () {
name = document.getElementById('userName').value;
pass = document.getElementById('password').value;
var oDate = new Date();
oDate.setDate(oDate.getDate() + 30);
// 寫入cookie
document.cookie = "userName=" + name + "; expires=" + oDate;
document.cookie = "password=" + pass + "; expires=" + oDate;
}
oBtn1.onclick = function () {
var oCookie = document.cookie.split('; ');
for (var i = 0; i < oCookie.length; i++) {
var temp = oCookie[i].split('=');
if (i == 1) {
document.getElementById('userName').value = temp[1];
};
if (i == 0) {
document.getElementById('password').value = temp[1];
};
};
}
}
</script>
</head>
<body>
<div>
<input type = "text" id = "userName" placeholder = "用戶名"> <br>
<input type="text" id = "password" placeholder = "密碼"> <br>
<input type="button" value = "保存" id = "save">
<input type="button" value = "從cookie讀取" id = "cokie">
</div>
</body>
</html>