1.html代码:
<div class="tree_menu"> <ul id="treeRoot"></ul> </div>
2.定义的json格式:json对象一般用双引号,并且文件编码方式为utf-8
[{ "id":"01", "name":"中国", "items":[{ "id":"0101", "name":"北京市", "items":[{ "id":"0101", "name":"东城区" }] }] }, { "id":"02", "name":"美国" }]
3.javascript解析json数组
var baseUrl = window.location.host; function createTreeNode(){ $.getJSON("http://"+baseUrl+"/json/js/treeData.json",function(data){ $("#treeRoot").empty(); var htmlstr = ''; $.each(data,function(itemsIndex,item){ htmlstr += "<li id='"+item.id+"'><span class='hitarea'>"+item.name+"</span>"; if(item.items && item.items.length > 0){ htmlstr +="<ul id='ul"+item.id+"' title='"+itemsIndex+"'></ul>"; } htmlstr +="</li>"; }); $("#treeRoot").append(htmlstr); function loadData(treeRoot,json){ var hitarea = treeRoot.find("li>span.hitarea"); var titAttr = treeRoot.find("ul").attr("title"); hitarea.each(function(i){ hitarea.eq(i).one("click",function(){ //第一次点击时加载子项 var itemUl = json[titAttr].items; var newUl = $(this).next("ul"); var html = ''; $.each(itemUl,function(indexItems,item){ html += "<li id='"+item.id+"'><span class='hitarea'>"+item.name+"</span>"; if(item.items && item.items.length > 0){ html +="<ul id='ul"+item.id+"' title='"+indexItems+"'></ul>"; } html +="</li>"; }); newUl.append(html); loadData(newUl,itemUl); //递归调用loadData方法 }) }) } loadData($("#treeRoot"),data); }) }; $(document).ready(function(){ createTreeNode(); })