我正在通过从json文件获取内容来完成此faq部分,这是我能够实现的。 但我的困惑是如何整合常见问题部分的“类别”标题?请分享一些如何实现它的想法。
//脚本
$.getJSON("faqs.json",function(data){
$.each(data.posts, function(i,data){
var faqs =
"<dt>"+data.title+"</dt><dd>"+data.answer+"</dd>";
$(faqs).appendTo("#faq");
});
});
// JSON格式是
{"posts": [
{ "title":"Question 1?", "answer":"faq answer 1" },
{ "title":"Question 2?", "answer":"faq answer 2" },
]}
//当前HTML输出
<dl id="faq">
<dt>Question 1?</dt><dd>faq answer 1</dd>
<dt>Question 2?</dt><dd>faq answer 2</dd>
</dl>
//预期的HTML out应为
<dl id="faq">
<strong>Category 1</strong>
<dt>Question 1?</dt><dd>faq answer 1</dd>
<dt>Question 2?</dt><dd>faq answer 2</dd>
<strong>Category 2</strong>
<dt>Question 1?</dt><dd>faq answer 1</dd>
<dt>Question 2?</dt><dd>faq answer 2</dd>
</dl>
如何在JSON文件中集成“类别”部分,如果是这样,我如何解析HTML。 提前致谢
答案 0 :(得分:2)
将JSON输出更改为:
{
"categories": [
{
"title": "Category 1",
"posts": [
{ "title":"Question 1?", "answer":"faq answer 1" },
{ "title":"Question 2?", "answer":"faq answer 2" }
]
},
{
"title": "Category 2",
"posts": [
{ "title":"Question 1?", "answer":"faq answer 1" },
{ "title":"Question 2?", "answer":"faq answer 2" }
]
}
]
}
将脚本更改为:
$.getJSON("faqs.json",function(data) {
$.each(data.categories, function(i, c) {
var section = "<strong>" + c.title + "</strong>";
$.each(c.posts, function(j, p) {
section += "<dt>" + p.title + "</dt><dd>" + p.answer + "</dd>";
});
$(section).appendTo("#faq");
});
});
但是,请记住,您所需的输出无效:强标记不应嵌套在dl标记中。