我正在努力寻找一种使用javascript为我的网站创建博客文章的方法。我精通javascript,但是除document.getElementById()
外,我没有使用过许多DOM元素。我正在寻求有关如何实现将JS对象转换为帖子的方法的支持。这是一个示例对象:
var posts = { //My object
firstPost: { //An example post
index: 1, //Identifies order of posts: 1 is oldest... >1 newest
id: "first", //An id for the post
date: { //Date will be listed next to name on post
month: 11,
day: 2,
year: 2018
},
name: "My Post", //Name of the post
text: "Text for the post...", //Actual Post
image: 'blogImage.png' //An image for the post
}
现在我想通过如下所示的函数传递它来创建HTML:
function assemblePost( index, id, month, day, year, text, image) {
//DOM GOES IN HERE
}
以下是我手动键入HTML时的外观示例:
<div class="card" id="first"> <!-- Card element links to css -->
<h2>My Post</h2> <!-- Name of the post -->
<h5>Posted November 2nd, 2018</h5> <!-- Date of the post -->
<div class="img" style="height:200px;"><img src="/blogImage.png" ></div>
<p>Text for the post..."</p> <!-- Actual Post -->
</div>
我不确定如何处理此问题,因为:
我意识到这是很多解释,示例和指南,但是,我非常感谢您的帮助!谢谢!
答案 0 :(得分:1)
只需逐步进行即可。
var posts = [ //My object (array of posts)
{ //An example post
index: 1, //Identifies order of posts: 1 is oldest... >1 newest
id: "first", //An id for the post
date: { //Date will be listed next to name on post
month: 11,
day: 2,
year: 2018
},
name: "My Post", //Name of the post
text: "Text for the post...", //Actual Post
image: 'blogImage.png' //An image for the post
},
{ //An example post
index: 2, //Identifies order of posts: 1 is oldest... >1 newest
id: "first", //An id for the post
date: { //Date will be listed next to name on post
month: 11,
day: 2,
year: 2018
},
name: "My another Post", //Name of the post
text: "Text for another post...", //Actual Post
image: 'blogImage.png' //An image for the post
}
];
const container = document.getElementById('div-posts');
posts.forEach(function(post) {
let div = document.createElement('div');
div.className = 'card';
div.id = 'post_' + post.index; //or post.id provided itis unique
//create more elements instead of ".innerHTML" if you wish
div.innerHTML = '<h2>' + post.name + '</h2>' +
'<h5>' + (new Date(post.date.year, post.date.month, post.date.day).toDateString()) + '</h5>' +
'<div class="img"><img src="/' + post.image + '" ></div>' +
'<p>' + post.text + '</p>';
container.appendChild(div);
});
.card {
border: solid 1px #ccc;
width: 400px
}
.img img {
max-width: 100%
}
<div id="div-posts"></div>