如何用纯JavaScript或jQuery将JS对象渲染为指定结构HTML
纯JavaScript实现方案
遍历数据对象的所有条目,按照目标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' } } // 执行渲染 function renderToPage() { // 遍历对象值,拼接对应结构的HTML const htmlContent = Object.values(data).map(item => ` <div> <h1>${item.title}</h1> <p>${item.content}</p> <p>${item.date}</p> </div> `).join(''); // 将内容插入到页面id为app的挂载节点 document.querySelector('#app').innerHTML = htmlContent; } renderToPage();
注意:如果数据字段里可能包含<>、脚本代码这类特殊内容,直接拼接字符串插入会有XSS安全风险,需要先对内容做转义处理。
jQuery实现方案
如果项目已经引入jQuery,可以通过逐元素创建的方式渲染,自动处理特殊字符转义,安全性更高:
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 $mountPoint = $('#app'); // 遍历数据对象 $.each(data, (key, item) => { // 创建对应结构的元素 const $card = $('<div>'); const $title = $('<h1>').text(item.title); const $content = $('<p>').text(item.content); const $date = $('<p>').text(item.date); // 组装结构后挂载到页面 $card.append($title, $content, $date); $mountPoint.append($card); });
内容的提问来源于stack exchange,提问作者noob_ettan
相关产品推荐
相关产品推荐

