如何从js对象完全创建HTML?

时间:2019-04-08 02:46:42

标签: javascript html dom

我正在努力寻找一种使用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>

我不确定如何处理此问题,因为:

  1. 类“ card”链接到CSS,但我不确定如何使用DOM来实现。
  2. 我不确定DOM是否可以编辑样式,例如在此示例中,图像高度为200,但是在另一幅图像中,图像高度可能有所不同。
  3. 对于我的许多其他帖子,我可能有多个段落和/或列表。至少,我想要一种创建一个文本字符串的方法。也许对于列表而言,数组在我的对象中最有用,但是我不确定如何处理多个段落。

我意识到这是很多解释,示例和指南,但是,我非常感谢您的帮助!谢谢!

1 个答案:

答案 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>