新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
html如何設(shè)置cookie
在HTML中設(shè)置cookie,可以使用JavaScript的document.cookie屬性,以下是詳細(xì)的步驟:

1、創(chuàng)建一個函數(shù)來設(shè)置cookie,這個函數(shù)需要接收三個參數(shù):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=/";
}
2、使用這個函數(shù)來設(shè)置cookie,設(shè)置一個名為username的cookie,值為JohnDoe,并在1天后過期:
setCookie("username", "JohnDoe", 1);
3、若要讀取cookie,可以創(chuàng)建一個函數(shù)來獲取指定名稱的cookie值。
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
4、使用這個函數(shù)來讀取cookie,讀取名為username的cookie值:
var username = getCookie("username");
console.log(username); // 輸出 "JohnDoe"
5、若要刪除cookie,可以創(chuàng)建一個函數(shù)來設(shè)置指定名稱的cookie值為空字符串,并設(shè)置過期時間為過去的時間。
function deleteCookie(name) {
setCookie(name, "", 1);
}
6、使用這個函數(shù)來刪除cookie,刪除名為username的cookie:
deleteCookie("username");
網(wǎng)頁名稱:html如何設(shè)置cookie
瀏覽地址:http://www.dlmjj.cn/article/dpdpjei.html


咨詢
建站咨詢
