【发布时间】:2019-11-23 02:22:04
【问题描述】:
如果您关闭了页面的某些元素,我将添加 cookie 以保存。当我关闭 cookieconsent 横幅时,cookie 有效,但是当我使用完全相同的代码获取其他 cookie 时,它不起作用。这是javascript:
function GetCookie(name) {
var arg=name+"=";
var alen=arg.length;
var clen=document.cookie.length;
var i=0;
while (i<clen) {
var j=i+alen;
if (document.cookie.substring(i,j)==arg)
return "here";
i=document.cookie.indexOf(" ",i)+1;
if (i==0) break;
}
return null;
}
function testFirstCookie(){
var offset = new Date().getTimezoneOffset();
if ((offset >= -180) && (offset <= 240)) { //Europe and America
var visit=GetCookie("cookieCompliancyAccepted");
if (visit==null){
$("#myCookieConsent").fadeIn(800); // Show warning
} else {
// Already accepted
}
}
var offset = new Date().getTimezoneOffset();
if ((offset >= -180) && (offset <= 240)) { //Europe and America
var visit=GetCookie("saveBannerClosed");
console.log(visit);
if (visit==null){
console.log("show");
$("#savebanner").show(); // Show banner
} else {
console.log("hide");
$("#savebanner").hide(); //hidden
}
}
}
$(document).ready(function(){
$("#cookieButton").click(function(){
console.log('Understood');
var expire=new Date();
expire=new Date(expire.getTime()+7776000000);
document.cookie="cookieCompliancyAccepted=here; expires="+expire+";path=/";
$("#myCookieConsent").hide(800);
});
$("#denySaveBanner").click(function(){
console.log('Save Banner Closed');
var expire=new Date();
expire=new Date(expire.getTime()+604800000);
document.cookie="saveBannerClosed=here; expires="+expire+";path=/";
$("#savebanner").hide();
});
testFirstCookie();
});
这是html:
<center>
<div id="savebanner" style="border:5px solid red; width:60%;">
<img
src="image/savebanner.jpg"
onclick='window.open("https://www.battleforthenet.com")'
width="100%"
/>
<br />
<button
style="background-color:red; color:white"
id="denySaveBanner"
>
No thanks, I want to pay more for a worse internet
</button>
<button
style="background-color:green; color:white"
onclick="window.open('https://battleforthenet.com');"
>
Show me how I can help
</button>
</div>
</center>
当您按下按钮时它会隐藏,但当您重新加载页面时它不会重新隐藏。我即将放弃这个,因为我已经尝试了大约一个月来解决这个问题。谢谢。
【问题讨论】:
-
如果您要使用 jquery、
<center>、元素和一个月的时间 - 为什么不使用经过验证的真正 cookie 插件:github.com/carhartl/jquery-cookie -
我会在 5-6 小时内完成。我在 chromebook 上,我真的不能做任何大规模的事情,因为......是的......它是一个 chromebook。
-
但是,它至少添加了 cookie
-
您能否进入 getCookie(或循环中的控制台日志 document.cookie.substring(i,j))并确保循环可以识别第一个之外的元素?我怀疑那里有一个错误......
-
好吧,你的代码不完整,所以我们无论如何也帮不上忙。 #cookieButton、#myCookieConsent、#denySaveBanner 和#savebanner 元素在哪里?如果您的计算机可以处理 StackOVerflow,它可以处理 cookie 插件 - 没有什么“大规模”的。
标签: javascript jquery html cookies