如何在localstorage中保存切换状态?

时间:2017-10-19 13:13:15

标签: javascript jquery

如何在此代码中使用localstorage来保存切换状态?

<html>
<head>
<script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
    $("button").click(function(){
      $(".price-box").fadeToggle(500,"swing");
    });
});
</script>
</head>
<body>

<div class="price-box">Show/hide this div</div>

<button>Toggle between hide() and show()</button>

</body>
</html>

非常感谢

1 个答案:

答案 0 :(得分:3)

您可以尝试类似

的内容
 $(document).ready(function() {
  if (window.localStorage.getItem("price-box") != null) {
    var pb = window.localStorage.getItem("price-box");
    if (pb == "true") {
      $(".price-box").hide();
    }
  }

  $("button").click(function() {
    var v = $(".price-box").is(":visible")
    $(".price-box").fadeToggle(500, "swing");
    window.localStorage.setItem("price-box", v)
  });
});

Demo