LocalStorage值未在HTML页面中显示

时间:2014-01-03 14:01:18

标签: jquery html5 forms local-storage

我能够成功存储日志值,但在同一域的另一个页面中显示记录的值时遇到问题。我通过localStorage中的first.html存储记录的值。我的代码是:

 <!DOCTYPE html> 
 <html lang="en"> 
 <head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
       //code of localStorage goes here     
       })
</script>
   </head>
   <body>
    <form id="logForm" method="post">
         <input type="text" name="project" value="Project Name">
         <input type="submit" value="Log Time">
      </form>
     <a href="otherpage.html">
        This is a link to otherpage.html
    </a>
 </body>
 </html>

我想在otherpage.html中显示记录的值。我在otherpage.html中的代码是:

 <!DOCTYPE html>
 <html>
 <body>
       <p>This page will show the logged values</p> 
       <ul id="theLog"></ul> 
   <button type="button" id="clearLog">Clear Log</button> 
 </body>
</html>

不幸的是,当我尝试显示otherpage.html时,ul没有显示任何内容。任何人都可以告诉我为什么它没有显示任何东西或建议一些替代方法在otherpage.html中显示它。附:我不想在同一页面上显示它。

1 个答案:

答案 0 :(得分:1)

您需要在otherpage.html上放置相应的功能,页面无法执行另一页上存在的功能。把它放在otherpage.html

$(function(){
function getAllItems() {
    var timeLog = ""; //the variable that will hold our html
    var i = 0;
    var logLength = localStorage.length-1; //how many items are in the database starting with zero

    //now we are going to loop through each item in the database
    for (i = 0; i <= logLength; i++) {
        //lets setup some variables for the key and values
        var itemKey = localStorage.key(i);
        var values = localStorage.getItem(itemKey);
        values = values.split(";"); //create an array of the values
        var q = values[0];


        //now that we have the item, lets add it as a list item
        timeLog += '<li><strong>'+q+'</strong>: ';
    }

    //if there were no items in the database
    if (timeLog == "")
        timeLog = '<li class="empty">Log Currently Empty</li>';

    $("#theLog").html(timeLog); //update the ul with the list items
}

getAllItems();
});