gpt4 book ai didi

javascript - 使用智能菜单jquery打印json

转载 作者:行者123 更新时间:2023-11-28 05:35:34 24 4
gpt4 key购买 nike

 {"menu" :[{ 
"name": "Computers",
"children": [{
"name": "Notebook",
"children": [{
"name": "Apple"
}, {
"name": "Windows"
}]
}, {
"name": "Tablets",
"children": [{
"name": "Apple"
}, {
"name": "Android"
}, {
"name": "Windows"
}]
}]
}, {
"name": "Phones",
"children": [{
"name": "Android",
"children": [{
"name": "Samsung"
}, {
"name": "Nokia"
}, {
"name": "Lenovo"
}]
}, {
"name": "Windows Phones",
"children": [{
"name": "Microsoft"
}, {
"name": "Nokia"
}]
}]
}, {
"name": "Cameras",
"children": [{
"name": "Digital",
"children": [{
"name": "Nikon"
}, {
"name": "Fuji"
}]
}, {
"name": "DSLR",
"children": [{
"name": "Canon"
}, {
"name": "Nikon"
}]
}]
}]
}

我想打印它,以便每个 parent 都有自己的 child ..这是我的代码

$(document).ready(function() {
$.ajax({
url: 'menuData.json',
type: 'get',
dataType: 'json',
error: function(data){
alert("error");
},
success: function(data){

var i=0;
var j=0;
var n=0;
var obj=data;
var json = JSON.stringify(obj);
var s = JSON.parse(json);
for( i=0;i<s.menu.length;i++){
$("#main-menu").append(' <li><a href="#">'+ s.menu[i].name +'</a></li>');
for( j=0;j<s.menu[i].children.length;j++)
{ $("#main-menu").append(' <li><a href="#">'+ s.menu[i].children[j].name + '</a></li>');
for( n=0;n<s.menu[i].children[j].children.length;n++){

$("#main-menu").append(' <li><a href="#">'+ s.menu[i].children[j].children[n].name +'</a></li>');

}

}
}

$('#main-menu').smartmenus({
subMenusSubOffsetX:1,
subMenusSubOffsetY: -8

});
}
});

});

但最终结果是这样的 enter image description here

请提供任何帮助..提前致谢..顺便说一句,我是初学者,所以请帮助我..再次感谢

最佳答案

您的代码在逻辑上是正确的,只是您总是附加到$("#main-menu")。考虑这样做:

...

for( var i=0; i < s.menu.length; i++)
{
$("#main-menu").append(' <li id="menu-list-' + i + '"><a href="#">' + s.menu[i].name + '</a></li>');

var list_length = s.menu[i].children.length;
if (list_length > 0)
$("#main-menu li#menu-list-" + i).append('<ul></ul>');

for( var j=0; j < list_length; j++)
{
$("#main-menu li#menu-list-" + i + " ul").append(' <li id="menu-list-' + i + '-children-list-' + j + '"><a href="#">'+ s.menu[i].children[j].name + '</a></li>');

var children_list_length = s.menu[i].children[j].children.length;
if(children_list_length > 0)
$("#main-menu li#menu-list-" + i + " ul li#menu-list-" + i + "-children-list-" + j).append("<ul></ul>");
for( var n=0; n < children_list_length; n++)
{
$("#main-menu li#menu-list-" + i + " ul li#menu-list-" + i + "-children-list-" + j + " ul").append(' <li><a href="#">'+ s.menu[i].children[j].children[n].name +'</a></li>');
}
}
}
...

关于javascript - 使用智能菜单jquery打印json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39393998/

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