我能够成功存储日志值,但在同一域的另一个页面中显示记录的值时遇到问题。我通过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
中显示它。附:我不想在同一页面上显示它。
答案 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();
});