【问题标题】:How to render object to html with pure javascript/jquery如何使用纯 javascript/jquery 将对象呈现为 html
【发布时间】:2021-03-27 05:39:51
【问题描述】:

如何使用纯 JavaScript 或 jQuery 将 JavaScript 对象呈现为 HTML?

data = {
  'this-is-title-123' : {
    title : 'this-is-title-123',
    content : 'Lorem ipsum dolor sit amet',
    date : '12.8.2009'
  },
  'this-is-title-456' : {
    title : 'this-is-title-456',
    content : 'the quick brown fox jumped',
    date : '18.2.2028'
  },
  'this-is-title-789' : {
    title : 'this-is-title-789',
    content : 'the jumped fox fell in a pit',
    date : '19.12.2020'
  }
}

我想像这样将它转换为 HTML:

<div>
  <h1>this-is-title-123</h1>
  <p>Lorem ipsum dolor sit amet</p>
  <p>12.8.2009</p>
</div>
<div>
  <h1>this-is-title-456</h1>
  <p>the quick brown fox jumped</p>
  <p>18.2.2028</p>
</div>
<div>
  <h1>this-is-title-789</h1>
  <p>the jumped fox fell in a pit</p>
  <p>19.12.2020</p>
</div>

【问题讨论】:

  • 想要的结果是什么?
  • this-is-title-123

    Lorem ipsum dolor sit amet

    12.8.2009

    this-is-title-456

    棕狐快跳了

    18.2.2028

    this-is-title-789

    跳跃的狐狸掉进坑里

    19.12.2020

    这就是我想要的,抱歉我不知道怎么做在这里格式化文本,我是stackoverflow的新手,我将所需的输出添加到问题
  • 欢迎来到SO,请转至stackoverflow.com/tour。 SO 不是免费的代码提供者,您必须先展示一些您尝试过的代码,我们会尽力帮助您使其变得更好

标签: javascript html javascript-objects


【解决方案1】:

它可以像迭代 object values 并更新 inner HTML 一样简单。

const data = {
  'this-is-title-123': {
    title: 'this-is-title-123',
    content: 'Lorem ipsum dolor sit amet',
    date: '12.8.2009',
  },

  'this-is-title-456': {
    title: 'this-is-title-456',
    content: 'the quick brown fox jumped',
    date: '18.2.2028',
  },

  'this-is-title-789': {
    title: 'this-is-title-789',
    content: 'the jumped fox fell in a pit',
    date: '19.12.2020',
  },
};

const posts = Object.values(data).map(post => `
  <div>
    <h2>${post.title}</h2>
    <p>${post.content}</p>
    <time>${post.date}</time>
  </div>
`)

document.querySelector('#root').innerHTML = posts.join('\n');
body {
  font-family: sans-serif;
}
&lt;div id="root"&gt;&lt;/div&gt;

【讨论】:

    猜你喜欢
    • 2019-05-26
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 2012-08-30
    • 1970-01-01
    相关资源
    最近更新 更多