gpt4 book ai didi

javascript - 需要知道如何使用 jQuery/JS 将这段 JSON 转换为 HTML

转载 作者:行者123 更新时间:2023-11-30 10:53:52 28 4
gpt4 key购买 nike

我需要知道如何使用 jQuery 和一些基本的 JavaScript 将以下 JSON 放入类名为 article 的元素中:

{"elements": [
{
"head": "story 1",
"writer": "journalist 1"
},
{
"head": "story 2",
"writer": "journalist 2"
}
]}

尝试实现以下 HTML。我对 JSON 等很陌生。希望通过示例学习如何......

<div class="article">
<h5>story 1</h5>
<p>By: journalist 1</p>

<h5>story 2</h5>
<p>By: journalist 2</p>
</div>

最佳答案

var data = {
"elements": [
{
"head": "story 1",
"writer": "journalist 1"
},
{
"head": "story 2",
"writer": "journalist 2"
}
]};

var result = []; /* where we will store the generated HTML */

$.each(data.elements, function() {
/* in this function, `this` refers to one of the [story] objects in the elements array */
result.push('<h5>');
result.push(this.head);
result.push('</h5><p>By: ');
result.push(this.writer);
result.push('</p>');
});

$('<div class="article" />') /* creates the div class="article" */
.html(result.join('')) /* merges the generated HTML from above and inserts it into the div*/
.appendTo(document.body); /* appends the div to the page */

关于javascript - 需要知道如何使用 jQuery/JS 将这段 JSON 转换为 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3465184/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com