[英]Want to set show/hide script visible by default
i want to set a show/hide js script that is using localstorage on by default. 我想设置默认情况下使用localstorage的show / hide js脚本。
$(document).ready(function () {
var sidebarVisible = localStorage.getItem('sidebar') == 'true';
$('#sidebar').toggle(sidebarVisible);
$('.bgcontainer_center').toggleClass('clicked', sidebarVisible);
$("#toggle").click(function () {
$("#sidebar").toggle("slow", function () {
localStorage.setItem('sidebar', $('#sidebar').is(':visible'));
});
$(".bgcontainer_center").toggleClass('clicked');
});
});
This is the link to it https://jsfiddle.net/eo12xw79/67/ 这是链接到它https://jsfiddle.net/eo12xw79/67/
I can't seem to find how to set it on by default. 我似乎找不到默认设置。
The reason it isn't toggled is because the sidebar
key isn't present in the browser's localstorage
the first time we visit the page. 之所以没有切换,是因为我们第一次访问该页面时,浏览器的
localstorage
没有sidebar
键。
There is a very simple solution, just have to check if the sidebar
key exists in the localstorage
and if not, create it. 有一个非常简单的解决方案,只需检查
sidebar
密钥是否在localstorage
,如果不存在,则创建它。
$(document).ready(function () {
// BEGIN
if(!localStorage.getItem('sidebar')) {
localStorage.setItem('sidebar', 'true');
}
// END
var sidebarVisible = localStorage.getItem('sidebar') == 'true';
$('#sidebar').toggle(sidebarVisible);
$('.bgcontainer_center').toggleClass('clicked', sidebarVisible);
$("#toggle").click(function () {
$("#sidebar").toggle("slow", function () {
localStorage.setItem('sidebar', $('#sidebar').is(':visible'));
});
$(".bgcontainer_center").toggleClass('clicked');
});
});
EDIT : I think it's useless, why ? 编辑:我认为这没用,为什么?
Because you will use the localstorage
for a single variable that has no real importance. 因为您将对没有真正重要性的单个变量使用
localstorage
。
After, this is only a personal opinion, it depends on your needs. 之后,这只是个人观点,取决于您的需求。
DUPLICATE : How to check whether a Storage item is set? 重复: 如何检查是否设置了存储项目?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.