我正在从数组创建 Jquery 菜单项
(function ($) {
var menu = [{
title: "Home",
href: "/"
}, {
title: "Item 1",
href: "/item2",
items: [{
title: "Sub",
href: "/sub"
}, {
title: "Sub",
href: "/sub"
}]
}, {
title: "Item 2",
href: "/item2",
items: [{
title: "sub2",
href: "/sub2"
}, {
title: "sub2",
href: "/sub2",
items: [{
title: "sub3",
href: "/sub3"
}, {
title: "Sub3",
href: "/sub3"
}, {
title: "sub3",
href: "/sub3"
}, {
title: "sub3",
href: "/sub3"
}]
}, {
title: "Item 3",
href: "/item3"
}]
}, {
title: "Item 4",
href: "/item4"
}];
$('nav').append(globalMenu(menu));
function globalMenu(el){
console.log(el)
var ul = $('<ul>')
$.each(el, function(){
var li = $('<li>')
li.append($('<a>', {text : this.title, href : this.href}));
ul.append(li)
if(this.items) li.after(globalMenu(this.items));
})
return ul;
}
}(jQuery));
问题是它错误地附加了 UL 的孩子。例如,子 UL 在父 UL 关闭后就坐在这样的位置:
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/item2">Item 1</a></li>
<ul>
<li><a href="/sub">Sub</a></li>
<li><a href="/sub">Sub</a></li>
</ul>
<li><a href="/item2">Item 2</a></li>
</ul>
</nav>
它的子 UL 应该像这样位于父项的内部:
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/item2">Item 1</a>
<ul>
<li><a href="/sub">Sub</a></li>
<li><a href="/sub">Sub</a></li>
</ul>
</li><!-- close parent LI here -->
<li><a href="/item2">Item 2</a></li>
</ul>
</nav>
谁能帮我解决这个问题?
这是小提琴:http: //jsfiddle.net/T7Fcm/