javascript - change Jquery object into <ul><li> -
i have following jquery object :-
(function ($) { var menu = [{ title: main1", href: "/" }, { title: "main2", href: "/main2", items: [{ title: "submain2_1", href: "/submain2_1" }, { title: "submain2_2", href: "/submain2_2" }] }, { title: "main3", href: "/main3", items: [{ title: "submain3_1", href: "/submain3_1" }, { title: "submain3_2", href: "/submain3_2", items: [{ title: "subsubmain3_1", href: "/subsubmain3_2" }, { title: "subsubmain3_2", href: "/subsubmain3_2" }] }, { title: "submain3_3", href: "/submain3_3" }] }, { title: "main4", href: "/main4" }]; });
and wish change
<ul> <li class="main"><a href="/">main1</a></li> <li class="main"><a href="/main2">main2</a></li> <ul> <li class="sub"><a href="/submain2_1">submain2_1</a></li> <li class="sub"><a href="/submain2_2">submain2_2</a></li> </ul> <li class="main"><a href="/main3">main3</a></li> <ul> <li class="sub"><a href="/submain3_1">submain3_1</a></li> <li class="sub"><a href="/submain3_2">submain3_2</a></li> <ul> <li class="subsub"><a href="/subsubmain3_1">subsubmain3_1</a></li> <li class="subsub"><a href="/subsubmain3_2">subsubmain3_2</a></li> </ul> <li class="sub"><a href="/submain3_3">submain3_3</a></li> </ul> <li class="main"><a href="/">main4</a></li> </ul>
how can achieve this?
thanks , time
you need use recursive function call everytime there array items
:
$('body').append(fnmenu(menu)); function fnmenu(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(fnmenu(this.items)); }) return ul; }
fiddle : http://jsfiddle.net/2hp9k/
Comments
Post a Comment