简体   繁体   English

将变量另存为JavaScript中的cookie?

[英]Save variable as cookie in Javascript?

I have a function that displays or hides a menu, but if I refresh the variable is reset to 0 . 我有一个显示或隐藏菜单的函数,但是如果刷新,该变量将重置为0 What I want is to keep the variable value it's currently at in between page refreshes, which I guess you do with cookies? 我想要的是保持页面刷新之间当前的变量值,我猜您是使用cookie吗? However I don't know how. 但是我不知道如何。

visible = 0; // Want this variable to keep it's value

function menu(id)
{
    if(visible == 0) {
        document.getElementById(id).style.display = "block";
        visible = 1;
    }
    else {
    document.getElementById(id).style.display = "none";
    visible = 0;
    }
}

Managing cookies in JavaScript is ugly unless you use a framework. 除非使用框架,否则在JavaScript中管理cookie很难。 The benefit of using a cookie is that you don't have to worry about compatibility with old browsers. 使用Cookie的好处是您不必担心与旧浏览器的兼容性。 However, if you don't care about old browsers then you can use HTML5 Local Storage (aka Web Storage), which allows you to persist basic key/value pairs of strings. 但是,如果您不关心旧的浏览器,则可以使用HTML5本地存储(又名Web存储),该存储使您可以保留基本的键/值对字符串。

HTML5 Local Storage (Web Storage) example HTML5本地存储(网络存储)示例

Demo: http://jsfiddle.net/9zsH4/ 演示: http//jsfiddle.net/9zsH4/

In the demo, try toggling the menu then refresh the page to see its state be persisted. 在演示中,尝试切换菜单,然后刷新页面以查看其状态。

function getVisible(){
    var value = localStorage.getItem('visible');
    return value == '1';
}

function setVisible(visible){
    localStorage.setItem('visible', (visible ? '1' : '0'));
}

function menu(id)
{
    if(!getVisible()) {
        document.getElementById(id).style.display = "block";
        setVisible(true);
    } else {
        document.getElementById(id).style.display = "none";
        setVisible(false);
    }
}

Cookie Example Cookie示例

This example uses the minimal framework from MDN here , so be sure to include the docCookies framework. 此示例使用了MDN的最小框架,因此请确保包含docCookies框架。

function getVisible(){
    var value = docCookies.getItem('visible');
    return value == '1';
}

function setVisible(visible){
    docCookies.setItem('visible', (visible ? '1' : '0'), new Date(2015, 5, 12));
}

function menu(id)
{
    if(!getVisible()) {
        document.getElementById(id).style.display = "block";
        setVisible(true);
    } else {
        document.getElementById(id).style.display = "none";
        setVisible(false);
    }
}

Edit: to explain this line: 编辑:解释这一行:

localStorage.setItem('visible', (visible ? '1' : '0'));

Here I'm using the ternary operator. 在这里,我正在使用三元运算符。 It's just a shorthand if/else, so it's the same as doing: if / else只是一个简写,所以和这样做一样:

if(visible){
    localStorage.setItem('visible', '1');
} else {
    localStorage.setItem('visible', '0');
}

Another example: get a human Yes/No representation of a boolean. 另一个示例:获取布尔值的人类是/否表示。

var something = true;
var humanText = something ? 'Yes' : 'No';
console.log(humanText); // Yes

var something = false;
var humanText = something ? 'Yes' : 'No';
console.log(humanText); // No

As you can see, the first part is evaluated and if the result equates to true , the question mark part is used, else the colon part is used. 如您所见,将评估第一部分,如果结果等于true ,则使用问号部分,否则使用冒号部分。

See this question for more examples. 有关更多示例,请参见此问题

Cookies are not appropriate for this, as they will be sent to the server with every request. Cookies不适合此操作,因为它们将随每个请求发送到服务器。

Instead, use storage. 而是使用存储。 Keep your current code and replace visible with localStorage.visible . 保留当前代码,并使用localStorage.visible替换visible This will allow the variable to persist across pageloads. 这将使变量在页面加载中保持不变。

Additionally, you will need to add if( localStorage.visible) document.getElementById('yourID').style.display = 'block'; 另外,您将需要添加if( localStorage.visible) document.getElementById('yourID').style.display = 'block'; independently of the menu function, so that when the page is loaded then the initial state is applied. 独立于menu功能,以便在加载页面时应用初始状态。

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

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