gpt4 book ai didi

javascript - JSON 数组到 Mustache

转载 作者:行者123 更新时间:2023-12-03 02:56:13 25 4
gpt4 key购买 nike

我正在尝试从 JSON 数组获取数据以显示在我的 Mustache 模板中。我已经这样做了好几个小时了,但我仍然不知道我错过了什么(或者可能错过了什么?)。

请注意,此特定任务要求我使用 let 而不是 var

这是我的代码:

HTML:

<script id="mustacheTemplate" type="x-tmpl-mustache">
<ul id="output">
{{#items}}
<li>{{title}}{{description}}</li>
{{/items}}
</ul>
</script>

JSON:

{ "items": [
{"title": "Mulan",
"description": "Based on the Chinese legend of Hua Mulan, and was Disney's 36th animated feature."
},
{"title": "Beauty and the Beast",
"description": "An adaptation of the fairy tale about a monstrous-looking prince and a young woman who fall in love."
},
{"title": "Aladdin",
"description": "Aladdin is a street-urchin who lives in Agrabah, a large and busy town, long ago with his faithful monkey friend Abu."
]},
}

Javascript:

console.log($);


$(document).ready(function() {

$.getJSON('../data/content.json', result);

function result (data, status){
console.log(data);

let template = $("#mustacheTemplate").html();

let content = data.items;

let output = Mustache.render(template, content);
console.log(output);

$('#output').html(output);
});
});

最佳答案

在传递渲染时,您需要传递数据而不是 data.item

在这里我评论了你的$.getJSON('../data/content.json', result);

可能对你有帮助

function result (data, status){
data={ "items": [
{"title": "Mulan",
"description": "Based on the Chinese legend of Hua Mulan, and was Disney's 36th animated feature."
},
{"title": "Beauty and the Beast",
"description": "An adaptation of the fairy tale about a monstrous-looking prince and a young woman who fall in love."
},
{"title": "Aladdin",
"description": "Aladdin is a street-urchin who lives in Agrabah, a large and busy town, long ago with his faithful monkey friend Abu."}
]
};
//console.log(data);

let template = $("#mustacheTemplate").html();
//console.log(template)
let content = data;

let output = Mustache.render(template, content);
//console.log(output);

$('#output').html(output);
}
$(document).ready(function() {

//$.getJSON('../data/content.json', result);


result(1,5);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.min.js"></script>
<script id="mustacheTemplate" type="x-tmpl-mustache">
<ul>
{{#items}}
<li>{{title}}{{description}}</li>
{{/items}}
</ul>
</script>

<div id="output"></div>

关于javascript - JSON 数组到 Mustache,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47604838/

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