简体   繁体   English

通过Cookie记住切换状态

[英]Remembering the toggle state via cookie

I was looking for a way to remember the toggle state and came across js-cookie on github. 我正在寻找一种方式来记住切换状态,并在github上遇到了js-cookie The document explains how to create, read and delete a cookie. 该文档说明了如何创建,读取和删除Cookie。 I was hoping for an example which could have helped me understand a lot better. 我希望有个例子可以帮助我更好地理解。

I need to toggle a form to show all fields or only the mandatory ones (form is a bit huge, but all fields aren't necessary, so thought of hiding ones which aren't and if the user somehow wish to furnish all detail can simply toggle to show all fields). 我需要切换一个表单以显示所有字段或仅显示必填字段(表单有点大,但是所有字段都不是必需的,因此请考虑隐藏不需要的字段,并且如果用户希望以某种方式提供所有详细信息,可以只需切换以显示所有字段)。

This toggle example is fairly simple. 这个切换示例非常简单。

HTML HTML

<html>
<head>
</head>
<body>
    <p>This is a paragraph.</p> 
    <button>Toggle between hide() and show()</button>
</body>
</html>

Javascript 使用Javascript

$("button").click(function(){
    $("p").toggle();
});

JSFiddle 的jsfiddle

The problem is when the form is reloaded the toggle state is forgotten. 问题是重新加载表单时,切换状态被忘记了。 I would like to use the js-cookie to remember the last toggle state (on or off). 我想使用js-cookie记住上一个切换状态(打开或关闭)。 How do I use this cookie to remember the state? 如何使用此Cookie记住状态?

You can use local storage of browser to store toggle state. 您可以使用浏览器的本地存储来存储切换状态。

$("button").click(function(){
    $("p").toggle();
    localStorage.setItem("toggleState","true");
});

var state=localStorage.getItem("toggleState");
if(state=="true"){
console.log("toggled");
}

EDITS: EDITS:

JS FIDDLE JS菲德尔

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM