为JSON文件中的每个新对象动态创建新DOM

时间:2017-03-10 18:55:23

标签: javascript jquery json

我是Javascript的新手,并尝试使用API​​。我有一个json文件,它是餐馆的每日菜单。

{
"meta": {
"generated_timestamp": 1489170614,
"requested_timestamp": 1489096800,
"ref_url": "http://www.sodexo.fi/sibat",
"ref_title": "Sibelius-Akatemia T-talo"
},
"courses": [
{
"title_fi": "Juustoista broilerpataa",
"title_en": "Cheesy chicken stew",
"category": "Campus-konsepti",
"properties": "G, L",
"desc_fi": "",
"desc_en": "",
"desc_se": ""
},
{
"title_fi": "Pinaattiohukaisia, puolukkasurvosta ja kermaviilikastiketta",
"title_en": "Spinach pancakes with lingonberry and sour cream sauce",
"category": "Vegetarian",
"properties": "L",
"desc_fi": "",
"desc_en": "",
"desc_se": ""
},
{
"title_fi": "Tomaattikeittoa",
"title_en": "Tomato soup",
"category": "Soup",
"properties": "G, L",
"desc_fi": "",
"desc_en": "",
"desc_se": ""
},
{
"title_fi": "Mango-valkosuklaamousse",
"title_en": "Mango and whitechocolate mousse",
"category": "Sweet",
"desc_fi": "",
"desc_en": "",
"desc_se": ""
}
]
}

我正试图以下列格式动态显示所有餐点:

<h2>ref_title</h2>
<p>title_fi(title_en)</p>
<p>category</p>
<p>desc_fi(desc_en)</p>

任何人都可以帮助我。我正在寻找append(),但我仍然很困惑。谢谢!

1 个答案:

答案 0 :(得分:1)

所以,我不太清楚ref_title是什么因为它不在数组中,所以我改为取代了title_fi:

以下代码将循环通过所有课程并将相关信息打印到

for (var i = 0, len = menu.courses.length; i < len; i++) {      
    $(".menu").append("<h2>" + menu.courses[i].title_fi + "</h2>"
                    + "<p>" + menu.courses[i].title_en + "</p>"
                    + "<p>" + menu.courses[i].category + "</p>"
                    + "<p>" + menu.courses[i].desc_en + "(" + menu.courses[i].desc_fi + ")</p>");
}

HTML:

<div class="menu">

</div>

这是一个方便的小提琴:

https://jsfiddle.net/nfnneil/vxetbnn9/1/