首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >关闭后不再向用户显示通知

关闭后不再向用户显示通知
EN

Stack Overflow用户
提问于 2020-05-11 10:48:44
回答 1查看 87关注 0票数 0

我已经在我的网站上创建了一个通知栏,我不希望在用户第一次关闭它后,在随后的访问中再次显示给他们。工具栏按预期工作,但我似乎无法让cookie正常工作而不再次显示它。我使用的是jquery cookie插件(我知道这个插件已经被替换了,但是我继承了这个站点)。

有没有人能帮我纠正我做错了什么?

代码语言:javascript
复制
$(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) { }
        });
    }
});
代码语言:javascript
复制
<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>

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-11 11:34:52

cookie属性丢失(您需要这个吗?),并且您从未实际检查过data-cookie

代码语言:javascript
复制
$(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) { }
        });
    }
});
代码语言:javascript
复制
<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>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61721508

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档