Bootstrap模态和cookie

时间:2014-10-29 12:28:21

标签: javascript jquery twitter-bootstrap cookies popup

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

这是我的Javascript:

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

这是我的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>

1 个答案:

答案 0 :(得分:7)

你的逻辑有点回到前面。你需要检查是否还没有设置cookie,然后显示模态。此外,您需要在之后设置cookie,以便它不会再次发生。

&#13;
&#13;
$(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=/";
    }
});
&#13;
<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>
&#13;
&#13;
&#13;