[英]creating list with sub items from json structure
I am creating a list with the below code which is contained in this fiddle . 我正在用此小提琴中包含的以下代码创建一个列表。
<ul></ul>
var myList = [{
"title": "Home",
"sub": 0,
"url": "/home",
"show": 1
}, {
"title": "News",
"sub": 0,
"url": "/news",
"show": 1
}, {
"title": "About",
"sub": 1,
"url": "/about",
"show": 1,
child: [{
"title": "Contact",
"sub": 0,
"url": "/about/contact",
"show": 1
}]
}, {
"title": "Other",
"sub": 0,
"url": "/other",
"show": 0
}];
$.each(myList, function (entryIndex, entry) {
var title = this.title;
var show = "";
var sub = '';
var url = this.url;
if (!this.show) {
show = "style=color:grey;";
}
if (this.sub) {
sub = $("ul").append(this.child.text);
console.log(sub);
}
$("ul").append("<li " + show + "> " + title + sub + "</li>");
});
The output I am getting is, which is working as expected except for the children of about. 我得到的输出是正常的,除了大约的孩子。
<ul>
<li> Home</li>
<li> News</li>
<li> About[object Object]</li>
<li style="color:grey;"> Other</li>
</ul>
How do I go about getting the children to appear so I get 我如何去让孩子出现,让我得到
<ul>
<li> Home</li>
<li> News</li>
<li> About
<ul>
<li> Contact</li>
</ul>
</li>
<li style="color:grey;"> Other</li>
</ul>
Try something like this: 尝试这样的事情:
$(document).on('ready',function(){
var data = [{/*... your data*/}] ;
var endMenu =getMenu(data);
function getMenu(d ){
return d.map(function(node){
var subMenu = ( node.child && node.child.length > 0) ? '<ul>'+ getMenu(node.child) + '</ul>' : "";
return '<li>'+node.title + subMenu + '</li>' ;
});
}
$('#menu').html('<ul>'+endMenu.join('')+ '</ul>');
});
All you have to do is to check is your object has child
items and if does you execute the function again getMenu(node.child)
, like: 您要做的就是检查您的对象是否有
child
项,是否再次执行getMenu(node.child)
函数,例如:
var subMenu = ( node.child && node.child.length > 0) ? '<ul>'+ getMenu(node.child) + '</ul>' : "";
Hopefully this will guide you to implement it in you version. 希望这将指导您在您的版本中实现它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.