如何解决如何使用javascript将json值转换为html?
我正在获取一个如下所示的 json 对象:
c 2940
然后我使用模板文字像这样在页面上附加对象
{
title: "My entry",entry: "I am a paragraph. I have <em>italics</em> and other styling html.
I am the second paragraph.
I am the third graf,here is a <a href='#'>link</a>. "
}
我遇到的问题是我希望 ${item.entry} 从 json 观察 html 和段落中断。我该怎么做?
解决方法
只需将所有换行符替换为 <br />
并正确设置锚标记的格式。
const content = document.getElementById("content");
const data = [{
title: "My entry",entry: "I am a paragraph. I have <em>italics</em> and other styling html.\n\I am the second paragraph.\nI am the third graf,here is a <a href='#'> link </a>."
}]
const myJson = data.map((item,index) => {
return `<div data-item="${index}">
<h2>${item.title}</h2>
${item.entry.replaceAll("\n","<br/>")}
</div>`;
});
content.innerHTML = myJson;
<div id="content"></div>
您可以使用以下正则表达式拆分 entry
:/\s*\n\s*/g
const content = document.querySelector('.content');
const out = {
response: {
items: [{
title: "My entry",entry: `I am a paragraph. I have <em>italics</em> and other styling html.
I am the second paragraph.
I am the third graf,here is a <a href='#'>link</a>.`
}]
}
};
const myHtml = out.response.items.map(({ title,entry },index) => `
<div data-item="${index}">
<h2>${title}</h2>
${entry.trim().split(/\s*\n\s*/g).map(p => `<p>${p}</p>`).join('')}
</div>
`).join('');
content.innerHTML = myHtml;
<div class="content"></div>
类似的东西?
var response = [{
title: "My entry",entry: 'I am a paragraph. I have <em>italics</em> and other styling html.\nI am the second paragraph.\n\nI am the third graf,here is a <a href="#">link</a>.'
}];
const myJson = response.map((item,index) => {
var entries = item.entry.split('\n');
entries_filtered = entries.filter(x => x != '');
var entries_html = entries_filtered.map(ent => `<p>${ent}</p>`).join('');
return `<div data-item="${index}">
<h2>${item.title}</h2>
${entries_html}
</div>`;
});
console.log(myJson);
没有正确的答案,有效的方法将取决于您的 HTML/CSS 样式决定。如下所述,您可以将 /n
替换为 <br />
标签、<p></p>
标签,或者您可以使用样式化的 div
/span
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。