【问题标题】:Keep added jquery classes after page refresh or page load在页面刷新或页面加载后保留添加的 jquery 类
【发布时间】:2018-07-31 06:32:30
【问题描述】:

我的 jquery 代码:请让我知道如何在重新加载页面后保留课程

$(document).ready(function(){   
  $("#themecolors li a").click(function(){
    $("#themecolors li a").removeClass("working");
    $(this).addClass("working");
  });

  $(".default-theme").click(function() {
    $("body").removeClass();
    $("body").addClass("one");
  });
 $(".green-theme").click(function() {
    $("body").removeClass();
    $("body").addClass("green_skin");           
    });
});

【问题讨论】:

  • 在值发生变化时将它们保存到localStorage / sessionStorage。阅读它们并在页面加载时应用它们
  • 请告诉我如何将值保存在 localStorage / sessionStorage 中。以及如何添加此代码。
  • 我强烈建议您阅读文档并自己发现“如何” ~ developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

标签: jquery


【解决方案1】:

检查下面的代码。您可以在单击时在本地存储中添加类值。 ans 在文档就绪时使用该本地存储。

 $("#themecolors li a").click(function(){
    $("#themecolors li a").removeClass("working");
    $(this).addClass("working");
    localStorage.ClassName = "working";
  });

$(document).ready(function() {
    SetClass();
});

function SetClass() {
//before assigning class check local storage if it has any value
    $("#themecolors li a").addClass(localStorage.ClassName);
}

【讨论】:

    【解决方案2】:

    你可以像这样使用你的代码

    jQuery(window).on("load", function() {
      $("#themecolors li a").click(function(){
      $("#themecolors li a").removeClass("working");
      $(this).addClass("working");
    });
    
    $(".default-theme").click(function() {
      $("body").removeClass();
      $("body").addClass("one");
    });
    $(".green-theme").click(function() {
     $("body").removeClass();
     $("body").addClass("green_skin");           
     });
    });
    

    【讨论】:

    • 我想在点击时添加类,在页面重新加载或刷新后保持添加相同。
    • 你可以使用 jQuery(window).on("load", function() { /* code */});而不是 $(document).ready(function(){ });我也更新了这段代码,请检查。
    【解决方案3】:

    页面重新加载时,JS文件会重新下载,所以不能在JS中保存状态。

    您可以为此使用 cookie。见这里:How do I set/unset a cookie with jQuery?

    【讨论】:

      猜你喜欢
      • 2015-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-14
      • 2011-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多