JavaScript中的Cookie操作代码:获取、设置和删除Cookie
JavaScript是一种常用的前端编程语言,在网页开发过程中,我们经常需要操作Cookie以实现一些功能。本文将介绍如何使用JavaScript获取、设置和删除Cookie的代码,帮助您更好地理解和应用Cookie相关知识。
获取Cookie的代码:
function getCookie(name) {
var cookieValue = "";
var cookies = document.cookie.split("; ");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].split("=");
if (cookie[0] === name) {
cookieValue = cookie[1];
break;
}
}
return cookieValue;
}
设置Cookie的代码:
function setCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
删除Cookie的代码:
function deleteCookie(name) {
document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}
用户评论