Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

local storage - jQuery - localStorage for toggling hidden class

By pressing .trigger the hidden class is toggled to show/hide the .box. I am trying to use localStorage to remember the last state of the .box i.e whether it has the hidden class or not.

How do I store whether each .box has class hidden, and then deliver the last selected state on page reload?

https://codepen.io/moofawsaw/pen/ExNPNyy

$(".box").toggleClass(localStorage.toggled);

$(document).ready(function() {
  $(".trigger").on("click", function() {
    var $this = $(this).closest(".item").find(".box");

    if (localStorage.toggled != "hidden") {
      $this.toggleClass("hidden", true);
      localStorage.toggled = "hidden";
    } else {
      $this.toggleClass("hidden", false);
      localStorage.toggled = "";
    }
  });
});
.item {
  display: flex;
  justify-content: space-between;
  border: 2px solid;
  width: 200px;
  padding: 1.3rem;
}

.trigger {
  cursor: pointer;
  background: blue;
  border: 1px solid;
  height: 60px;
  width: 60px;
}

.box {
  background: red;
  border: 1px solid;
  height: 40px;
  width: 40px;
}

.box.hidden {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item">
  <div class="trigger"></div>
  <div class="box hidden"></div>
</div>
<div class="item">
  <div class="trigger"></div>
  <div class="box hidden"></div>
</div>
question from:https://stackoverflow.com/questions/66054648/jquery-localstorage-for-toggling-hidden-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The syntax to write a data item in the current domain's localStorage object is:

localStorage.setItem('key', 'value');

The syntax for reading is as follows:

let key = localStorage.getItem('key');

In your code you're not following the above syntax, but trying to access to an unknown localStorage.toggled property.
You should fix your JS code like this:

$(".box").toggleClass(localStorage.getItem("toggled"));
$(document).ready(function () {
  $(".trigger").on("click", function () {
    let $this = $(this).closest(".item").find(".box");
    if (localStorage.getItem("toggled") != "hidden") {
      $this.toggleClass("hidden", true);
      localStorage.setItem("toggled", "hidden");
    } else {
      $this.toggleClass("hidden", false);
      localStorage.setItem("toggled", "");
    }
  });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...