twitter-bootstrap Bootstrap 模态和 cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26630373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 21:46:18  来源:igfitidea点击:

Bootstrap modal and cookie

javascriptjquerytwitter-bootstrapcookiespopup

提问by fnk

I have created a bootstrap modal popup and it appears and disappears perfectly. What I need to do is check to see if there is a cookie stored and only have the popup appear once while the user is on the site. I have a close button on it too. At the moment it appears every time I refresh the page and I'm not sure how to get it to work. I have seen a couple of examples by googling but nothing works for me. Can anyone help? Thanks

我创建了一个引导模式弹出窗口,它完美地出现和消失。我需要做的是检查是否存储了 cookie,并且当用户在网站上时,弹出窗口只出现一次。我也有一个关闭按钮。目前,每次刷新页面时它都会出现,但我不确定如何让它工作。我通过谷歌搜索看到了几个例子,但对我没有任何作用。任何人都可以帮忙吗?谢谢

Here is my Javascript:

这是我的Javascript:

$(document).ready(function () {
    if (document.cookie != "") {
        $("#myModal").modal("show");
        $("#myModalClose").click(function () {
          $("#myModal").modal("hide");
        });
    }
});

Here is my HTML:

这是我的 HTML:

<div id="myModal" class="modal fade in">
    <div class="inner-modal">
        <div class="modal-container">
            <p>some text</p>
            <button class="close" data-dismiss="modal" data-target="#myModal">Hide this message</button>
        </div>
    </div>  
</div>

回答by DavidG

Your logic is a bit back to front. You need to check if no cookie has yet been set then show the modal. Also you need to set the cookie afterwards so it doesn't happen again.

你的逻辑有点前后颠倒。您需要检查是否尚未设置 cookie,然后显示模态。您还需要在之后设置 cookie,以免再次发生。

$(document).ready(function () {
    //if cookie hasn't been set...
    if (document.cookie.indexOf("ModalShown=true")<0) {
        $("#myModal").modal("show");
        //Modal has been shown, now set a cookie so it never comes back
        $("#myModalClose").click(function () {
            $("#myModal").modal("hide");
        });
        document.cookie = "ModalShown=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/";
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

<div id="myModal" class="modal fade in">
    <div class="inner-modal">
        <div class="modal-container">
            <p>some text</p>
            <button id="myModalClose" class="close" data-dismiss="modal" data-target="#myModal">Hide this message</button>
        </div>
    </div>  
</div>