Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - How to save the collapse state on reload Bootstrap 5

I am new at bootstrap and javascript. How can I save the collapsed state so that the state retains on-page refresh?

<p>
  <button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
    Collapse Button
  </button>
</p>
<div class="collapse" id="collapseExample">
  <div class="card card-body">
    Makers Academy engineering project has commenced. We have had a great experience so far with rails and now feel like we are getting to grips with the more complicated aspects. This guide is a quick introduction into adding likes to posts.
  </div>
</div>

And my Javascript attempt which isn't working.

$(document).ready(function () {
    $(".collapse").on("shown.bs.collapse", function () {
        localStorage.setItem("coll_" + this.id, true);
    });

    $(".collapse").on("hidden.bs.collapse", function () {
        localStorage.removeItem("coll_" + this.id);
    });
    
    $(".collapse").each(function () {
        if (localStorage.getItem("coll_" + this.id) === "true") {
            $(this).collapse("show");
        }
        else {
            $(this).collapse("hide");
        }
    });
});
question from:https://stackoverflow.com/questions/65941994/how-to-save-the-collapse-state-on-reload-bootstrap-5

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

1 Answer

0 votes
by (71.8m points)

It does work - see this fiddle.

I see you're using $ notation - so you'll need jQuery loaded too. Make sure it's loaded before bootstrap.js.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...