我已经在我的网站上创建了一个通知栏,我不希望在用户第一次关闭它后,在随后的访问中再次显示给他们。工具栏按预期工作,但我似乎无法让cookie正常工作而不再次显示它。我使用的是jquery cookie插件(我知道这个插件已经被替换了,但是我继承了这个站点)。
有没有人能帮我纠正我做错了什么?
$(document).ready(function () {
if ($("#notification-bar").length > 0) {
setTimeout(function () {
$("#notification-bar").animate({ height: "100px" }, 500);
}, 500);
$("#notification-bar .close").click(function (e) {
e.preventDefault();
var $notifBar = $("#notification-bar");
$notifBar.css("display", "none");
var cookieName = $notifBar.attr("data-cookie");
var d = new Date();
d.setTime(d.getTime() + 90 * 24 * 60 * 60 * 1000);
try {
document.cookie =
"closed_" + cookieName + "=1;expires=" + d.toUTCString() + ";path=/";
} catch (ignore) { }
});
}
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="notification-bar">
<div class="container">
This is the notification bar!
</div>
<a href="#" class="close">X</a>
</div>
发布于 2020-05-11 11:34:52
cookie属性丢失(您需要这个吗?),并且您从未实际检查过data-cookie。
$(document).ready(function () {
// fake document.cookie for testing
var document = {cookie:""};
if ($("#notification-bar").length > 0 && document.cookie.indexOf("closed_" + $("#notification-bar").attr("data-cookie")+"=1") < 0) {
setTimeout(function () {
$("#notification-bar").animate({ height: "100px" }, 500);
}, 500);
$("#notification-bar .close").click(function (e) {
e.preventDefault();
var $notifBar = $("#notification-bar");
$notifBar.css("display", "none");
var cookieName = $notifBar.attr("data-cookie");
var d = new Date();
d.setTime(d.getTime() + 90 * 24 * 60 * 60 * 1000);
try {
document.cookie =
"closed_" + cookieName + "=1;expires=" + d.toUTCString() + ";path=/";
} catch (ignore) { }
});
}
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="notification-bar" data-cookie="notifbar">
<div class="container">
This is the notification bar!
</div>
<a href="#" class="close">X</a>
</div>
https://stackoverflow.com/questions/61721508
复制相似问题