Reputation: 560
$(function () {
var data;
$.getJSON("menu.json", function(data){
//console.log(data);
//console.log(data.menu);
//console.log(data.menu.length);
//console.log(data.menu[1].link);
//getMenuItem(data);
var $menu = $("#menu");
console.log($menu);
console.log(this);
console.log(data)
$.each(data.menu, function () {
$menu.append(getMenuItem(data));
//console.log(this);
});
// //$menu.menu();
//getMenuItem(data);
});
function getMenuItem(data) {
var i = 0;
while(i<data.menu.length){
var item = $("<li>").append($("<a>",
{
href: '#' + data.menu[i].link,
html: data.menu[i].name
}));
//console.log(data.menu[i]);
if (data.sub) {
var subList = $("<ul>");
$.each(data.sub, function () {
subList.append(getMenuItem(this));
// //console.log(this);
// //console.log(subList);
});
item.append(subList);
// //console.log
}
i+=1;
console.log(i);
return item;
}
}
/*optional stuff to do after success */
// console.log(data);
// console.log(jsonD);
// for(i=0;i<data.menu.length;i++){
// console.log(data.menu[i].sub);
// }
});
This is my js(jquery) file. I am trying to fetch data from a json file which is located locally. This is a multilevel list. When I run the code it doesn't fetch the entire json data but only gets a the first item on the list. Can anyone help?
Also here is my json file
{
"menu" : [{
"name": "Croatia",
"link": "0",
"sub": null
}, {
"name": "England",
"link": "1",
"sub": [{
"name": "Arsenal",
"link": "0-0",
"sub": null
}, {
"name": "Liverpool",
"link": "0-1",
"sub": null
}, {
"name": "Manchester United",
"link": "0-2",
"sub": null
}]
}, {
"name": "Spain",
"link": "2",
"sub": [{
"name": "Barcelona",
"link": "2-0",
"sub": null
}, {
"name": "Real Madrid",
"link": "2-1",
"sub": null
}]
}, {
"name": "Germany",
"link": "3",
"sub": [{
"name": "Bayern Munich",
"link": "3-1",
"sub": null
}, {
"name": "Borrusia Dortmund",
"link": "3-2",
"sub": null
}]
}]
}
P.S #menu is ul, also answers in jquery please
Upvotes: 2
Views: 70
Reputation: 171669
Within the first each
don't pass in data
array to getMenuItem()
just pass in the object instance the same way you do with the recursive call to getMenuItem(this)
Then remove the while()
loop
// loop over array
$.each(data.menu, function(i, item) {
// get menu item for each object instance
$menu.append(getMenuItem(this));
});
function getMenuItem(obj) {
var item = $("<li>").append($("<a>", {
href: '#' + obj.link,
html: obj.name
}));
if (obj.sub) {
var subList = $("<ul>");
$.each(obj.sub, function() {
subList.append(getMenuItem(this));
});
item.append(subList);
}
return item;
}
Upvotes: 2