-1

我正在尝试加载基于访问网页之前存储的 localStorage 表达式的 div。例如,如果布尔值为真,那么显示 div 的简单方法是什么?我看过很多例子,但其中大多数接缝有点令人困惑。

谢谢。

4

2 回答 2

1

您可以简单地检查 localStorage 上的变量...

var item = window.localStorage.getItem('item') === "true";
if(item){
    //load your div;
}else{
    //do stuff
}

更新小提琴

于 2013-09-19T22:13:31.700 回答
0

这里有两个简单的辅助函数,可以帮助您将对象/布尔值等保存到 localStorage

function SetObject(key, value) {
    /// <summary>
    /// Sets object to localStorage as <key, value> pair
    /// This function will automatically stringify given object.
    /// </summary>
    /// <param name="key">Key object</param>
    /// <param name="value">Value object</param>

    try  {
        localStorage.setItem(key, JSON.stringify(value));
        console.log("Set Data [" + key + "] Value");
        console.log(value);
    } catch (exception) {
        if (exception.name === 'QUOTA_EXCEEDED_ERR' || exception.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
            console.error("Quota exceeded! Clear localStorage to solve problem. WARNING: Clearing localStorage will delete all user data.");
        } else {
            console.error("Unknown error while trying to set an item \"" + key + "\" with value: ");
            console.log(value);
        }
    }
};

function GetObject(key) {
    /// <summary>
    /// Gets object from localStorage as value for given key
    /// This function will automatically parse localStorage value and return object type
    /// </summary>
    /// <param name="key">Key object</param>
    /// <returns>Object from localStorage that corresponds to given key</returns>

    var value = localStorage.getItem(key);
    var parsedValue = value && JSON.parse(value);
    console.log("Get Data [" + key + "] of Value");
    console.log(parsedValue);
    return parsedValue;
};

然后,您可以使用它们来检索/保存对象/布尔值到 localStorage

// This will be executed when document DOM finished loading
$(document).ready(function() {
    // Retrieve 'SomePropertyKey' value from localStorage and 
    // compare check if it's 'true'
    if (GetObject("SomePropertyKey") == true) {
        // jQuery call to change div's style 'display' to value 'block'
        $("#divId").show();
    }
});

HTML

<div id="divId" style="display: none;">...</div>
于 2013-09-19T22:19:02.147 回答