如何通過以下代碼將 2 個月后到期的 cookie 添加到“[email protected]”
<div id="home">
<div class="name" my-data="123">Email: [email protected]</div>
</div>
我認為實際時間的代碼應該如下,但我不知道如何為其添加值:
function myemail () {
var expiryDate = new Date();
expiryDate.setMonth(expiryDate.getMonth() 2);
document.cookie = cookieName '=y; expires=' expiryDate.toGMTString
uj5u.com熱心網友回復:
假設你有權限給你的 div 添加一個 ID,下面的代碼作業正常
<body>
<div id="home">
<div class="name" my-data="123" id="email-div">Email: [email protected]</div>
<button onclick="myemail()">Set it</button>
</div>
<script>
function myemail() {
var expiryDate = new Date();
var email = document.getElementById("email-div").textContent.split("Email:")[1]
expiryDate.setMonth(expiryDate.getMonth() 2);
document.cookie = 'emailCookie=' email ';expires=' expiryDate.toGMTString() ';path=/';
}
</script>
</body
好吧,我使用了一個按鈕來觸發操作。在任何情況下,您都可以這樣做。
uj5u.com熱心網友回復:
toGMTString 是一個函式,需要呼叫。將 expiryDate.toGMTString 替換為 expiryDate.toGMTString()
const Cookie = {
get: function (name) {
const nameEq = name "=";
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i ) {
let 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;
},
set: function (name, value, hours) {
const expires = "";
if (hours) {
let date = new Date();
date.setTime(date.getTime() (hours * 60 * 60 * 1000));
const expires = "; expires=" date.toGMTString();
}
document.cookie = name "=" value expires "; path=/";
}
};
您可以更改hours為任何內容,當然也可以更改為date.setTime(date.getTime() (hours * 60 * 60 * 1000));相應的公式
用法`
放: Cookie.set('myemail', '[email protected]', 1460) // 1460 is 2 months in hours
得到: Cookie.get('myemail')
const email = document.getElementsByClassName('name')[0].textContent.split(' ')[1]; Cookie.set('myemail', email, 1460);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/324891.html
標籤:javascript html
上一篇:單擊跨度元素時,模態不會關閉
下一篇:創建多語言單頁網站的最簡單方法
