【问题标题】:LocalStorage value is not getting displayed in HTML pageLocalStorage 值未显示在 HTML 页面中
【发布时间】:2014-01-03 22:24:17
【问题描述】:

我能够成功存储日志值,但在同一域的另一个页面中显示日志值时遇到问题。我通过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>

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

【问题讨论】:

  • 但是您没有在 otherpage.html 上调用 localStorage...。您希望在这里发生什么?
  • 如何在otherpage.html上拨打localStorage
  • var myHtml = localStorage['key']
  • 需要在otherpage.html中包含相应的javascript,但可以跨页面访问localStorage

标签: jquery html forms local-storage


【解决方案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();
});

【讨论】:

  • 我已将这些放在script 中,但仍然没有任何反应
  • 请确保你也有这个:&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"&gt;&lt;/script&gt;
猜你喜欢
  • 2023-03-08
  • 1970-01-01
  • 2013-12-08
  • 1970-01-01
  • 1970-01-01
  • 2018-04-07
  • 1970-01-01
  • 2011-09-12
  • 1970-01-01
相关资源
最近更新 更多