首页 > 解决方案 > 如何在没有 cookie 的会话中仅显示一次警报信息框

问题描述

我在引导程序 3 中创建了一个警报信息框,并设法创建它在 10 秒后消失。但我希望这个框只显示一次浏览器会话(而不是在每个页面重新加载时显示现在的样子)。

不喜欢使用 cookie,而是使用 sessionStorage

这是我的html代码:

    <div class="alert alert-info alert-success credits center" role="alert">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h2>text </h2> text 2
                    <div class="row margin-t-10">
                 <div class="col-md-3 col-xs-5 col1 center-block">
                       <a href="#"><button class="button btn-success btn-block" > text 3<span style="font-size:17px;" aria-hidden="true"></span></button></a>
                    </div>
           </div>
    </div>

这是我的 JS 代码:

window.setTimeout(function() {
$(".alert-credit, .alert-info").fadeTo(1000, 0).slideUp(1000, function(){
    $(this).remove(); 
});
}, 9000);

我怎样才能知道警报信息框只显示一次会话?

标签: javascripttwitter-bootstrap-3

解决方案


您只需要在sessionStorage显示警报时保存一个条目,并在显示警报之前检查它是否存在:

if(sessionStorage.getItem('alertShown') === null){
  window.setTimeout(function() {
      $(".alert-credit, .alert-info").fadeTo(1000, 0).slideUp(1000, function(){
          sessionStorage.setItem('alertShown', 'true');
          $(this).remove(); 
      });   
  }, 9000);
}else{
    $(".alert-credit, .alert-info").remove();
}

推荐阅读