我创建了一个内容储物柜(点击链接打开内容),但现在我卡在了cookie部分。点击特定链接后,内容储物柜不得再出现30天。我已经创建了onclick cookie并且它可以工作,但我似乎无法设置cookie必须保留的天数(无论我将其设置为会话cookie)我也不知道如何阅读pageload上的cookie,以便它不再显示内容锁定器。我根本不是一个javascript专家,到目前为止我所管理的一切都来自谷歌搜索。这是我的代码
myDate = new Date('31/12/2020 12:00 UTC');
document.cookie = 'clicklink=yes; expires=' + myDate.toString + ';';
的onclick = “警报(document.cookie中);” >
请帮忙
答案 0 :(得分:3)
设置Cookie:
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
获取cookie:
function getCookie(cname) {
var name = cname + "=";
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);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
检查页面加载中是否存在cookie
function checkCookieOnLoad() {
if(getCookie("clicklink") === "yes") {
// Show content and hide clicklink
document.getElementById("content").style.display = "none";
document.getElementById("clink").style.display = "initial";
} else {
// Hide content and show clicklink
document.getElementById("content").style.display = "initial";
document.getElementById("clink").style.display = "none";
}
}
HTML
<div id="content"> Some content that i want to show on click</div>
<a href="http://www.google.com/" target="_blank" onclick="setCookie('clicklink', 'yes', 30)" id="clink">Visit this to unlock</a>
详细了解link
我建议你阅读HTML5 storage APIs。它类似于cookie但更有效和简单
答案 1 :(得分:2)
Chris声明:
您可以阅读有关Cookie here的更多信息。
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function showCookie(){
document.write(document.cookie);
}
设置cookie:
<button onclick="setCookie('clicklink', 'yes', 30)">Create cookie.</button>
显示Cookie:
<button onclick="showCookie()">Show cookie.</button>
当然这应该使用eventListener来完成,因此不容易被篡改。
获取cookie的功能:
function getCookie(cname) {
var name = cname + "=";
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);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
检查您的Cookie是否已设置:
var cookieString = getCookie("clicklink");
if(cookieString == "yes"){
// do something.
}