jquery 遍历 json
<HTML> <HEAD> <meta http-equiv="content-Type" content="text/html;charset=utf-8"> <TITLE></TITLE> <style></style> <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <script type="text/javascript"> <!--json Data--> var menulist = { "name":"bobo", "menulist": [ { "MID": "M001", "MName": "首页", "Url": "#", "menulist": "" }, { "MID": "M002", "MName": "车辆买卖", "Url": "#", "menulist": [ { "MID": "M003", "MName": "新车", "Url": "#", "menulist": [ { "MID": "M006", "MName": "奥迪", "Url": "#", "menulist": "" }, { "MID": "M007", "MName": "别克", "Url": "#", "menulist": "" } ] }, { "MID": "M004", "MName": "二手车", "Url": "#", "menulist": "" }, { "MID": "M005", "MName": "改装车", "Url": "#", "menulist": "" } ] }, { "MID": "M006", "MName": "宠物", "Url": "#", "menulist": "" } ] }; <!--js Code--> $(function () { $("#btn_bianli").click(function () { }); var showlist = $("<ul></ul>"); showall(menulist.menulist, showlist); $("#div_menu").append(showlist); }); //menu_list为json数据 //parent为要组合成html的容器 function showall(menu_list, parent) { for (var index in menu_list) { //如果有子节点,则遍历该子节点 if (menu_list[index].menulist.length > 0) { //创建一个子节点li var li = $("<li></li>"); var ul = $("<ul></ul>"); //将li的文本设置好,并马上添加一个空白的ul子节点,并且将这个li添加到父亲节点中 $(li).append(menu_list[index].MName).append(ul).appendTo(parent); //将空白的ul作为下一个递归遍历的父亲节点传入 showall(menu_list[index].menulist, ul); } //如果该节点没有子节点,则直接将该节点li以及文本创建好直接添加到父亲节点中 else { $("<li></li>").append(menu_list[index].MName).appendTo(parent); } } } </script> </HEAD> <BODY> <button id="btn_bianli">#btn_bianli</button> <div id="div_menu" class="tree well"></div> </BODY> </HTML>
显示效果
完全引用自: http://blog.163.com/hks_blog/blog/static/21492609020151113344248/