javascript - 如何使用纯 javascript/jquery 将对象呈现为 html
问题描述
如何使用纯 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>
解决方案
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;
}
<div id="root"></div>
推荐阅读
- java - 如何修复“java.lang.ClassCastException:活动必须实现片段的回调”
- pentaho - 如何获取 pentaho 报表设计器和 BI 服务器日志文件?
- events - 列出 github 存储库的私有事件?
- python - 在 pandas 数据帧上应用 np.isin() 的意外行为
- javascript - 使用 Audio 对象在 iframe 中创建的静音音频
- r - 编写函数时出现“意外的'}'错误并且无法说明原因
- android - Recyclerview Scroll State 使用 ViewPager 上的 Room 和 LiveData 保存
- javascript - 网站导航工具栏上的访问级别控制
- vba - 使用哪个 APDU 来读取/写入 MIFARE Ultralight NFC 标签上的记录?
- ios - 使用苹果硬件在 ubuntu 上构建 ios 应用程序