使用jQuery cookie或本地存储保存.addClass

我每次保存样式表时都试图保存.addClass,以便按钮记住

用户可以打开/关闭选项。

我的简单html:

这是我的代码:

  $(document).ready(function() { if ($.cookie("css")) { $("#bg").attr("href", $.cookie("css")); } $("#btn-switch button").click(function() { $("#bg").attr("href", $(this).attr('data-color')); $("#btn-switch .active").removeClass("active"); $(this).addClass("active"); $.cookie("css", $(this).attr('data-color'), { expires: 365, path: '/' }); return false; }); });  

如何使用相同的cookie来保存.active类? 我也会使用本地存储所有这些,但我不知道如何启动我上面实现的代码片段

这是一种使用localstorage的方法:

给定此标记(我在此示例中使用input type =“radio”):

 


Background

在脚本中,侦听单选按钮上的更改事件。 对于任何已检查的无线电都会触发此操作。 首先将#bg href设置为单击的radio的color data-attribute(使用jQuery .data() )。 然后将此href存储到localstorage。 另外,将单击选项的ID存储到localstorage。 然后在后续页面加载中使用localstorage中的项目来设置正确的href并激活正确的单选按钮:

 $(document).ready(function() { var csshref = localStorage["css"]; if (csshref) { $("#bg").prop("href", csshref); } var activeid = localStorage["activeid"]; if (activeid) { $("#" + activeid).prop("checked", true).closest("label").addClass("active"); } $('#btn-switch [type="radio"]').on("change", function() { $("#bg").attr("href", $(this).data('color')); localStorage.setItem('css', $(this).data('color')); localStorage.setItem('activeid', $(this).prop('id')); return false; }); }); 

这是一个DEMO

在演示中,尝试检查和关闭然后再次打开RUN。 您将看到后续运行记住检查了哪个项目并适当地设置了href。

这是一个简单的方法:

  $(document).ready(function () { //on page load check for cookie value and add active class if($.cookie("isButtonActive") == 1) { $("#btn-switch button").addClass("active"); } $("#btn-switch button").click(function() { //your previous code here if($("#btn-swtich button").hasClass("active") == true) { //button was active, de-activate it and update cookie $.("#btn-switch button").removeClass("active"); $.cookie("isButtonActive", "0"); } else { //button is not active. add active class and update cookie. $.("#btn-switch button").addClass("active"); $.cookie("isButtonActive", "1"); } }); });