javascript - 使用本地存储站点隐藏模式不起作用
问题描述
我有 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');
}
})
})
不幸的是,在我单击不再显示按钮后,它会关闭模式,但是当我刷新页面时,它会再次出现。
我的代码有什么问题?
解决方案
无论任何条件如何,都会在您的 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');
});
});
希望这可以帮助 :)
推荐阅读
- css - 在 img 上使用 object-fit 时单击图像外的事件
- c++ - 用 hypen '-' 标记字符串后,hypen 将被消除!如何在 C++98 中解决这个问题
- c# - 无法在任务内运行 ping?
- javascript - 表单提交输入未运行我的 onClick 功能
- prometheus - Spring boot 2.3.4 - Kafka 指标在 /actuator/prometheus 中不可见
- python - 从维基百科页面的类别中获取更一般的类别
- python - 如何在两个向量之间生成一个随机向量?
- javascript - XMPP - 如何删除两个 jid 之间的所有消息,但仅限于一个用户?
- c# - 从移动设备将提货单推送到结账终端
- node.js - 如何在 NodeJS 中对 MySQL 数据库进行异步调用