localstorage如何保存div

时间:2014-10-26 14:05:50

标签: javascript html local-storage

我需要使用localstorage保存div。当我按下按钮时,div变为可见但是当我关闭浏览器并再次打开它时,div需要可见。

到目前为止,这是我的代码:

<script>
function openDiv() {
    var film = document.getElementById("bookingDiv");
    if(film.style.display == "none"){
        film.style.display = "block";
    }
}

function save() {
    openDiv()
    var saveDiv = document.getElementById("bookingDiv")
    if(saveDiv.style.display == "block"){

    localstorage.setItem("text", saveDiv)

    }

}

function load() {
    var loadDiv = localstorage.getItem("text")
    if(loadDiv){

        document.getElementById("bookingDiv") = loadDiv

    }

}   

</script>

<body onload="load()">


<input type="button" id="testButton" value="Save" onclick="save()" />
<div style="display:none" id="bookingDiv" type="text">
hello
</div>


</body>

1 个答案:

答案 0 :(得分:1)

您只能使用localStorage存储字符串。所以你必须存储这个元素的状态而不是元素本身。

function save() {
    openDiv();
    var saveDiv = document.getElementById("bookingDiv");
    if (saveDiv.style.display == "block") {

        localStorage.setItem("isTextVisible", true);

    }

}

function load() {
    var isTextVisible = localStorage.getItem("isTextVisible");
    if (isTextVisible == "true") {

        openDiv();

    }

}

注意:不要忘记每个语句后面的分号,因为它可能会导致错误的行为!

相关问题