【问题标题】:How to save the collapse state on reload Bootstrap 5如何在重新加载 Bootstrap 5 时保存折叠状态
【发布时间】:2021-02-20 16:27:55
【问题描述】:

我是 bootstrap 和 javascript 的新手。如何保存折叠状态以保持页面刷新状态?

<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>

我的 Javascript 尝试不起作用。

$(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");
        }
    });
});

【问题讨论】:

    标签: javascript bootstrap-5


    【解决方案1】:

    它确实有效 - 请参阅 this fiddle

    我看到你正在使用$ 表示法 - 所以你也需要加载 jQuery。确保它在 bootstrap.js 之前加载。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-23
      • 2012-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-08
      • 2011-03-19
      相关资源
      最近更新 更多