需要在页面加载时显示/隐藏基于布尔表达式的div元素

时间:2013-09-19 22:06:27

标签: javascript html html5 dom

我正在尝试加载基于在进入网页之前存储的localStorage Expression的div。如果布尔值为真,那么显示div的简单方法是什么?我看过很多例子,但是大多数例子都让人感到有些困惑。

感谢。

2 个答案:

答案 0 :(得分:1)

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

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

Updated Fiddle

答案 1 :(得分: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>