对于学校项目,我尝试使用HTML5本地存储创建论坛。在这里,人们可以创建并提交一个简单的帖子,但我不知道如何在一个页面上列出下面的所有帖子。这就是我所拥有的:
<form id="createpost" action="forum.html">
<input type="text" id="name">
<input type="text" id="age">
<input type="text" id="topic">
<input type="submit" id="submit">
</form>
所以在页面&#34; forum.html&#34;必须出现所有创建的帖子。我已经知道如何在本地存储中设置项目,但我不知道如何在一个页面上显示彼此之下的所有帖子。
如果你能帮助我,我真的很感激!提前谢谢!
答案 0 :(得分:0)
让我们以论证为例,说明您将所有帖子存储为对象,例如:
localStorage = [
{
name: "John Doe",
age: "20",
topic: "Being anonymous"
},
{
name: "Jane Doe",
age: "20",
topic: "Finding John"
},
];
(另外,假设您正在使用jquery,并且有一个div&#39;帖子&#39;)。 您可以使用一些Javascript本机函数遍历每个对象,并将它们转换为列表:
localStorage.map(function(forumPost){
$('.posts').append( "<ul>
<li>"forumPost.name"</li>
<li>"forumPost.age"</li>
<li>"forumPost.topic"</li>
</ul>")
});
答案 1 :(得分:0)
好的,所以你知道如何存储物品:
localStorage.setItem(key, value);
你如何存储你的帖子?我会使用这样的对象数组:
var posts = [{
topic: 'localstorage forum',
user: 'John Doe' }, {
topic: 'another topic',
user: 'Eleina'
}];
我会存储并获取这样的数据:
//store
localStorage.setItem("posts", JSON.stringify(posts));
//get
var posts = JSON.parse( localStorage.getItem("posts") || "[]" );
因为它是一个数组,你可以循环遍历它并根据它创建HTML:
html = '';
for(var i=0; i<posts.length; i++) {
html += '<div class="post">';
html += '<b>' + posts[i].topic + '</b> by ' + posts[i].user;
html += '</div>';
}
//output the html somehow, with jquery that could be
$("body").append(html);
希望这会有所帮助:)