Output:<html> <head> <title>Dynamic Menu - codesstore.blogspot.com</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> var menuItems = { "menu-0": { "id": "menu-0", "title": "Home", "parentId": null, "childCount": 0 }, "menu-1": { "id": "menu-1", "title": "About", "parentId": null, "childCount": 2 }, "menu-3": { "id": "menu-3", "title": "About Sub1", "parentId": "menu-1", "childCount": 2 }, "menu-5": { "id": "menu-5", "title": "About Sub2", "parentId": "menu-1", "childCount": 0 }, "menu-4": { "id": "menu-4", "title": "About Sub1 sub1", "parentId": "menu-3", "childCount": 0 }, "menu-6": { "id": "menu-6", "title": "Contact", "parentId": null, "childCount": 2 }, "menu-7": { "id": "menu-7", "title": "Contact sub1", "parentId": "menu-6", "childCount": 0 }, "menu-8": { "id": "menu-8", "title": "Contact sub2", "parentId": "menu-6", "childCount": 1 }, "menu-9": { "id": "menu-9", "title": "Contact sub2 sub1", "parentId": "menu-8", "childCount": 0 }, "menu-10": { "id": "menu-10", "title": "About Sub1 sub2", "parentId": "menu-3", "childCount": 2 }, "menu-11": { "id": "menu-11", "title": "About Sub1 sub2 sub1", "parentId": "menu-10", "childCount": 0 } , "menu-12": { "id": "menu-11", "title": "About Sub1 sub2 sub2", "parentId": "menu-10", "childCount": 0 } }; $(document).ready(function () { var htmlTxt = ""; var cat = []; var htmlStrTxt = ""; function recurseMenu(parent, level) { htmlStrTxt = '<ul>'; for (var x in menuItems) { if (menuItems[x].parentId == parent) { htmlStrTxt += '<li><span class="level-' + level + '">' + menuItems[x].title + '</span>'; if (menuItems[x].childCount > 0) { htmlStrTxt += recurseMenu(menuItems[x].id, level + 1); } htmlStrTxt += '</li>'; } } return htmlStrTxt + '</ul>'; } var htmlTxt = recurseMenu(null, 0); $("#menu").html(htmlTxt); }); </script> </head> <body> <div id="menu"> </div> </body> </html>
Recursively print a menu in JavaScript
Dynamically print a menu using recursive JavaScript method call.
Subscribe to:
Post Comments (Atom)
Nice coding and elaboration...
ReplyDeleteGood Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
ReplyDeletePython Training in electronic city
DataScience with Python Training in electronic city
AWS Training in electronic city
Big Data Hadoop Training in electronic city
Devops Training in electronic city
blockchain Training in electronic city
Hibernate Training in electronic city