希望我可以用一种有意义的方式来解释我的问题。
我在单击按钮时更改CSS主题,并且在单击特定主题的按钮时,它将类名保存到LocalStorage,但是由于LocalStorage键和值一直在变化,所以我只想调用任何单击后设置为本地存储,而不是特定值。我使用jQuery进行按钮单击,并且在下面包含了我的代码,对您的帮助将不胜感激。
$(document).ready(function(){
$('#dark').click(function(){
$('#app-root').removeClass();
$('#app-root').addClass('theme-dark');
localStorage.clear();
localStorage.setItem('theme-dark', ['theme-dark']);
localStorage.getItem('theme-dark');
});
$('#light').click(function(){
$('#app-root').removeClass();
$('#app-root').addClass('theme-light');
localStorage.clear();
localStorage.setItem('theme-light', ['theme-light']);
localStorage.getItem('theme-dark');
});
$('#beaker').click(function(){
$('#app-root').removeClass();
$('#app-root').addClass('theme-beaker');
localStorage.clear();
localStorage.setItem('theme-beaker', ['theme-beaker']);
localStorage.getItem('theme-dark');
});
$('#outrun').click(function(){
$('#app-root').removeClass();
$('#app-root').addClass('theme-outrun');
localStorage.clear();
localStorage.setItem('theme-outrun', ['theme-outrun']);
localStorage.getItem('theme-dark');
});
var localItem = localStorage.getItem('theme-outrun');
$('body').addClass(localItem);
});
答案 0 :(得分:0)
使用一个键在本地存储中设置不同的主题
$(document).ready(function(){
$('#dark').click(function(){
$('#app-root').removeClass();
$('#app-root').addClass('theme-dark');
localStorage.clear();
localStorage.setItem('theme', ['theme-dark']);
localStorage.getItem('theme');
});
$('#light').click(function(){
$('#app-root').removeClass();
$('#app-root').addClass('theme-light');
localStorage.clear();
localStorage.setItem('theme', ['theme-light']);
localStorage.getItem('theme');
});
$('#beaker').click(function(){
$('#app-root').removeClass();
$('#app-root').addClass('theme-beaker');
localStorage.clear();
localStorage.setItem('theme', ['theme-beaker']);
localStorage.getItem('theme');
});
$('#outrun').click(function(){
$('#app-root').removeClass();
$('#app-root').addClass('theme-outrun');
localStorage.clear();
localStorage.setItem('theme', ['theme-outrun']);
localStorage.getItem('theme');
});
var localItem = localStorage.getItem('theme');
$('body').addClass(localItem);
});
答案 1 :(得分:0)
您可以对所有localstorage.setItem和getItem使用相同的键
或
最后做
var localItem = localStorage.getItem(Object.keys(localStorage)[0])
$('body').addClass(localItem);