12

我正在尝试创建一个引导警报框,它会记住用户何时单击关闭按钮。我想我需要将该信息存储在 cookie 中。理想情况下,该 cookie 只会持续到当前会话,然后他们返回该框将再次出现。

我正在使用 jQuery-Cookie 插件。我上传到/jquery-cookie-master. 插件可以在这里找到

这是我到目前为止通过遵循此处找到的代码所得到的。

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="/jquery-cookie-master/jquery.cookie.js"></script>
<script>
    function runOnLoad(){
        if($.cookie('alert-box') == null) {
            $.cookie('alert-box', 'open', { expires: 7 });
        } else if($.cookie('alert-box') == 'close') {
            $(".close").hide();
        }

</script>

HTML:

<body onload="runOnLoad()">

<div class="alert alert-info">
  <button type="button" class="close" data-dismiss="alert" href="hideMe.php" onclick="hideMe()">×</button>
  <p>
    <strong>FORUM UPGRADE:</strong> In light of our recent surge in popularity we upgraded our forum and unfortunately lost all the old threads in the process.
  </p>
  <p>
    In an effort to kick-start the forum again we need your help. Sign up now and leave a post (it's free). Once we reach 100 threads every member will receive a special gift.
  </p>
  <p>
    <a href="http://example.com/forum/#/entry/register">
      <strong>Sign up to the forum now</strong>
    </a>.
  </p>
</div>

</body>

不幸的是,它不起作用。当我单击关闭按钮时,它不记得该操作,如果我刷新页面,警报框将再次出现。

我做错了什么?

4

1 回答 1

16

代码问题

  • 在您的代码onload功能中,您似乎正在设置 cookie 值,这很奇怪,因为您只想在用户关闭警报框时设置 cookie。

  • 你的按钮有一个href属性。这不是必需的,也是无效的 html。

解决方案

为了简单地隐藏和记住警报框的状态,您必须将事件绑定到关闭按钮,以便您知道用户何时单击关闭。

要使用 jQuery 绑定事件,您可以使用以下代码:

// When document is ready replaces the need for onload
jQuery(function( $ ){

    // Grab your button (based on your posted html)
    $('.close').click(function( e ){

        // Do not perform default action when button is clicked
        e.preventDefault();

        /* If you just want the cookie for a session don't provide an expires
         Set the path as root, so the cookie will be valid across the whole site */
        $.cookie('alert-box', 'closed', { path: '/' });

    });

});

要隐藏警报框,您只需检查正确的 cookie 值并隐藏该框:

jQuery(function( $ ){

    // Check if alert has been closed
    if( $.cookie('alert-box') === 'closed' ){

        $('.alert').hide();

    }

    // ... Binding code from above example

});
于 2012-12-04T09:07:47.717 回答