首页 > 解决方案 > 我无法弄清楚这个单一的脚本问题

问题描述

我一直在尝试寻找一种方法将我的 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>

标签: javascripthtml

解决方案


您的代码中有很多错误。正如其他人所提到的,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');
}

推荐阅读