我是编程新手,并尝试从头开始创建一个博客,不仅可以提高我的编码技能,而且这个博客将记录我的学习过程。
我想创建一种类型的管理页面,而不是将每个新帖子硬编码到索引.html页面,该页面具有两个input
字段 type="text"
,一个用于帖子标题,另一个用于帖子内容。我的提交按钮将从这些字段中获取我的用户输入,并将它们存储在一个对象中,该对象是我的makePost
构造函数,反过来,每个对象将存储在一个名为 posts
的数组中。
然后我想遍历数组并为每个帖子打印出每个对象的各个属性......每个属性title
、date
、content
。到目前为止,我能够创建一个具有这三个属性的对象并将其存储在数组的零索引中(array[0]
),但是当我使用 for 循环打印出对象以迭代我的数组时,它会打印整个对象......我想我需要在我的 for 循环中访问这些属性中的每一个?
我也意识到在这个代码块中我正在打印到控制台,但我只是为了确保某些东西正常工作。在代码结束时,我发布了它在控制台中打印的内容。现在我只需要分解该对象中的每个属性,并将它们打印在各自的 HTML 标记中。
在我决定发布之前,我已经搜索了几天,但我找不到任何特定于我尝试使用 JavaScript 做的事情的内容。提前感谢您的帮助。
这是我到目前为止的代码:
document.getElementById('button').onclick = function() {
var title = document.getElementById('title').value;
var content = document.getElementById('content').value;
var posts = [];
var makePost = function(title, content) {
return {
title: title,
date: Date(),
content: content
}
}
posts.unshift(makePost(title, content));
for (var i = 0; i < posts.length; i++) {
var myPost = posts[i];
console.log(myPost);
}
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
form {
position: relative;
top: 20px;
left: 20px;
margin-bottom: 50px;
}
h3 {
margin: 10px;
}
#title {
margin: 10px;
}
#date {
margin: 10px;
}
#content {
margin: 10px;
}
<h3>Type the content that you would like to show in the post section of the blog</h3>
<form class="form" action="index.html" method="post">
Title:<input id="title" type="text" name="name" value="" placeholder="Type title here"><br />
<!-- Date:<input id="date" type="text" name="name" value="" placeholder="Type date here"><br /> -->
Content:<input id="content" type="text" name="name" value="" placeholder="Type content here">
<input id="button" type="button" name="name" value="Submit">
</form>
<h2 id="displaytitle">This is the title of the post</h2>
<h2 id="displaydate">This is the date of the post</h2>
<h2 id="displaycontent">This is the content of the post</h2>
以下是它打印到控制台的内容:
Object {title: "This is my title", date: "Fri Feb 19 2016 09:54:37 GMT-0800 (PST)", content: "This is my content"}
for (var i = 0; i < posts.length; i++) {
var myPost = posts[i];
for(var key in myPost) {
console.log(myPost[key]);
}
}
要遍历数组并打印出众所周知的属性,请使用以下命令:
posts.forEach(function(post) {
console.log("Title: " + post.title);
console.log("tDate: " + post.date);
console.log("tContent: " + post.content);
}
for (var k in target){
if (target.hasOwnProperty(k)) {
alert("Key is " + k + ", value is" + target[k]);
}
}