javascript - 我无法弄清楚这个单一的脚本问题
问题描述
我一直在尝试寻找一种方法将我的 div 保存在本地存储中,这样它就不会再次出现,但我无法让它工作
<div>
<!-- Button to hide
* may add js to locally save and not showup again--> <button type="button" class="btn btn-primary btn-sm"
onclick="hidediv()">Understood</button>
<script>
function hidediv() {
var x = document.getElementById("hidemeonclick");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
if (localStorage.getItem(hidediv) === 1) {
// Local Storage to grab and locally hide div for {IPUSER}
console.log("Function Failed")
} else {
console.log("div hidden")
x.style.display === "none";
}
}
</script>
</div>
解决方案
您的代码中有很多错误。正如其他人所提到的,localStorage 仅存储字符串,因此您不应将严格与数字进行比较。您还使用 === 运算符将 style.display 设置为 none。不太确定您要在这里做什么,但是此代码将根据单击的按钮持续隐藏一个 div
<div id="hidemeonclick">I'll be hidden</div>
<button id='btn' onclick="hidediv()">Click me to hide div</button>
if (localStorage.getItem('hidediv') === 'hide') {
var x = document.getElementById("hidemeonclick");
x.style.display = "none";
}
function hidediv() {
var x = document.getElementById("hidemeonclick");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
localStorage.setItem('hidediv', 'hide');
}
推荐阅读
- java - Java 无向图距离计算
- amazon-web-services - 通过 AppSync 上的自定义 Lambda 授权方对突变进行身份验证
- javascript - 评级星级 PHP/JS
- angular - 使用角度 2 动态添加复选框
- php - 如何从 laravel 中的自定义配置数组中添加标题?
- windows - makecert -sk keyname 选项有什么意义?
- c# - (Unity C#) NullReferenceException 仅在 Start() 函数之外
- html - 引导选择器不显示选项
- r - 有没有一种简单的方法可以使用 Windows 10 在 R Markdown 上运行 bash 脚本?
- redis - 如何使用 Apache Beam 实验功能