jQuery中each循环json正确的该怎么写?
需求:根据后台传来的json数据循环出一个多级导航菜单
问题:
1、循环时二级和三级子菜单li标签外层包裹ul标签怎么写?
2、我这样写是否正确?有没有更好的写法?应该怎样写?
ps:本人小白,还望大神耐心指点。多谢
json数据大概如下:
[
{ "id":"1" , "name":"类型一","type":"a",
"cc":[
{ "id":"1-1" , "name":"二级1.1","type":"bb" },
{ "id":"1-2" , "name":"二级1.2","type":"cc",
"cc":[
{ "id":"1-1-1" , "name":"三级1.1.1","type":"aaa" },
{ "id":"1-1-2" , "name":"三级1.1.2","type":"bbb" },
{ "id":"1-1-3" , "name":"三级1.1.3","type":"ccc" },
{ "id":"1-1-4" , "name":"三级1.1.4","type":"ddd" }
]},
{ "id":"1-3" , "name":"二级1.3","type":"dd" },
{ "id":"1-4" , "name":"二级1.4","type":"ee" }
]
},
{ "id":"2" , "name":"类型二","type":"b",
"cc":[
{ "id":"2-1" , "name":"二级2.1","type":"ff" },
{ "id":"2-2" , "name":"二级2.2","type":"gg",
"cc":[
{ "id":"2-2-1" , "name":"三级2.2.1","type":"fff" },
{ "id":"2-2-2" , "name":"三级2.2.2","type":"ggg" },
{ "id":"2-2-3" , "name":"三级2.2.3","type":"hhh" },
{ "id":"2-2-4" , "name":"三级2.2.4","type":"iii" }
]},
{ "id":"1-3" , "name":"二级2.3","type":"hh" },
{ "id":"1-4" , "name":"二级2.4","type":"ii" }
]},
{ "id":"3" , "name":"类型三","type":"c" },
{ "id":"4" , "name":"类型四","type":"d" }
]
jquery代码如下:
$(function () {
$.ajax({
type: "post",
url: "./json/test.json",
success: function (data) {
$.each(data, function(index, content){
var showList = $("<li class='nav" + content.id + "'> "+ content.name +" </li>");
$.each(data[index].cc,function (i,k) {
var showC = $("<li class='list" + k.id + "'> "+ k.name +" </li>");
$.each(data[index].cc[i].cc,function (m,n) {
var showCC = $("<li class='list" + n.id + "'> "+ n.name +" </li>");
showC.append(showCC)
});
showList.append(showC)
});
$(".nav-list").append(showList);
});
}
});
});
HTML 代码如下:
<ul class="nav-list"></ul>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
用递归就可以了,不管有多少层级都适用
循环没问题,前面的朋友说的也是循环中append的影响性能,直接先拼成一个html字符串或使用documentfragment,最后一次append
直接拼成一个字符串append进去
你这样写性能太差了,可以拼接成一个字符串,在循环最后执行
http://www.aijquery.cn/Html/j...