我正在尝试将json文件解析为我的html但没有成功。这是我的Json文件:
{
"menu":[
{
"id":"contact",
"leaf":true,
"description":"testing",
"link":"",
"content":"contactUs.html",
"cssClass":"static-content",
"menu":null
},
{
"id":"rules",
"leaf":false,
"description":"Sports",
"link":"",
"content":"",
"cssClass":"",
"menu":[
{
"id":"types",
"leaf":true,
"description":"Wager",
"link":"",
"content":"wagerTypes.html",
"cssClass":"static-content wager-types",
"menu":null
},
{
"id":"odds",
"leaf":true,
"description":"Odds",
"link":"",
"content":"oddsAndLines.html",
"cssClass":"static-content",
"menu":null
},
{
"id":"policies",
"leaf":true,
"description":"Policies",
"link":"",
"content":"rulesAndPolicies.html",
"cssClass":"static-content rules-policies",
"menu":null
},
{
"id":"bonuses",
"leaf":true,
"description":"onuses",
"link":"",
"content":"sportsBonuses.html",
"cssClass":"static-content",
"menu":null
}
]
},
{
"id":"conditions",
"leaf":false,
"description":"Conditions",
"link":"",
"content":"",
"cssClass":"",
"menu":[
{
"id":"termsOfService",
"leaf":true,
"description":"Service",
"link":"",
"content":"termsOfService.html",
"cssClass":"static-content",
"menu":null
},
{
"id":"privacy",
"leaf":true,
"description":"Privacy Policy",
"link":"",
"content":"policy.html",
"cssClass":"static-content",
"menu":null
}
]
},
{
"id":"view",
"leaf":true,
"description":"View in: Mobile | Full Site",
"link":"",
"content":"delete.html",
"cssClass":"static-content",
"menu":null
}
]
}
此刻我就是这样:
var menu = [];
$.getJSON( "menu.json", function( data ) {
var items = [];
$.each( data.menu, function( key, url, val ) {
items.push( "<li id='" + key.id + "'> <a href=' "+ url.content +" '> " + val.description + "</a></li>" );
});
$( "<ul/>", {
"class": "dropDownList",
html: items.join( "" )
}).appendTo( "#wrapper" );
});
如果我只使用2个参数,我可以从Json文件中获取描述但是如果我添加另一个参数似乎我得到了一个错误... 如何访问所有内容,以及如何从菜单中获取值。
感谢。
答案 0 :(得分:0)
看起来你需要一个递归渲染
function process(data, $ct) {
if (!data || !data.length) {
return;
}
var $lis = $.map(data, function (menu, i) {
var $a = $('<a />', {
href: menu.content,
text: menu.description
});
var $li = $('<li >', {
id: menu.id
}).append($a)
if (menu.menu && menu.menu.length) {
process(menu.menu, $li)
}
return $li.get();
});
$("<ul/>", {
"class": "dropDownList",
html: $lis
}).appendTo($ct);
}
process(data.menu, '#wrapper')
演示:Fiddle