jQuery 可以通過 jquery.cookie.js 插件來操作 Cookie
官方地址
Github 地址
使用 jquery.cookie.js 之前需要先引入 jQuery:
<script src="/path/to/jquery.min.js"></script>
<script src="/path/to/jquery.cookie.js"></script>
我們可以使用第三方資源庫引入這兩個文件:
<script src="https://cdn.staticfile.org/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
完整代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="lib/jquery/dist/jquery.js"></script>
<script src="js/jquery.cookie.js"></script>
</head>
<body>
<input id="btnShow" type="button" value="創建cookie" />
<input id="btnLogin" type="button" value="獲取cookie" />
<input id="btnLoginCors" type="button" value="刪除cookie" />
<script>
$("#btnShow").click(function () {
var time = new Date();
var year = time.getFullYear();
var month = time.getMonth();
var day = time.getDate();
var hour = time.getHours();
var minute = time.getMinutes();
var second = time.getSeconds();
var time_stamp = hour.toString() + minute.toString() + second.toString();
console.log("123a【" + hour + ":" + minute + ":" + second + "】");
$.cookie('username', 'liudehua');
$.cookie('password', 'abcd123456', { expires: 7 });
$.cookie('age', '100', { expires: 7, path: '/' });
$.cookie('time', time_stamp);
});
$("#btnLogin").click(function () {
console.log("123b【" + $.cookie('username') + "】");
console.log("所有cookie【" + JSON.stringify($.cookie()) + "】");
});
$("#btnLoginCors").click(function () {
$.removeCookie('username');
$.removeCookie('age', { path: '/' }); // => true
console.log("123c")
});
</script>
</body>
</html>
*
*
*
*
*