2014-10-26 45 views
-4

我需要使用localstorage保存div。当我按下一个按钮的div变得可见,但是当我关闭浏览器并再次打开div需要可见。localstorage如何保存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

您只能使用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(); 

    } 

} 

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