首页 > 解决方案 > 使用本地存储站点隐藏模式不起作用

问题描述

我有 bootstrap 4 modal 弹出窗口,它会自动出现在我的页面中,我添加了一个不再显示的按钮

这是我到目前为止所拥有的。

HTML

 <div class="modal-footer">
        <button id="dont_show" class="btn-sm dont-show_again" type="button" data-dismiss="modal" >Dont show again</button>             
    </div>

js

$(document).ready(function(){
    var currentLocation = window.location.pathname + window.location.search;

    if(currentLocation =="/create-movie"){
        $(document).ready(function(){
            $("#myModal").modal();
        })

    }else{

    }

     var dontShowId =document.getElementById('dont_show');
     dontShowId.addEventListener('click', function(){
        var isshow = localStorage.getItem('status');
        console.log(isshow);
          if (isshow == null) {
              localStorage.setItem('status', 'shown');
                console.log(isshow);
              // Show popup here
              $('#myModal').modal('show');
          } else if(isshow != null) {
             $('#myModal').modal('hide');
          }
     })

})

不幸的是,在我单击不再显示按钮后,它会关闭模式,但是当我刷新页面时,它会再次出现。

我的代码有什么问题?

标签: javascriptjqueryhtmlbootstrap-4

解决方案


无论任何条件如何,都会在您的 javascript 代码中显示模式弹出窗口。尽管您在按钮的单击事件上设置了 localStorage,但您从不使用它来检查初始加载。这是您的代码的最小简化版本,可帮助您入门。

代码:

$(document).ready(function() {
  // onload decide baseed on localStorage
  var isshow = localStorage.getItem('status');
  var currentLocation = window.location.pathname + window.location.search;
  if (currentLocation == "/create-movie" && isshow != 'shown')
    $('#dont_show').modal('show');

  // on click set localStorage
  var dontShowId = document.getElementById('dont_show');
  dontShowId.addEventListener('click', function() {
    if (isshow == null)
      localStorage.setItem('status', 'shown');
  });

});

希望这可以帮助 :)


推荐阅读