jquery解析json异步功能树

1.html代码:

    


    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 += "
  • "+item.name+""; if(item.items && item.items.length > 0){ htmlstr +="
      "; } htmlstr +="
    • "; }); $("#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 += "
    • "+item.name+""; if(item.items && item.items.length > 0){ html +="
        "; } html +="
      • "; }); newUl.append(html); loadData(newUl,itemUl); //递归调用loadData方法 }) }) } loadData($("#treeRoot"),data); }) }; $(document).ready(function(){ createTreeNode(); })




        你可能感兴趣的:(jquery解析json异步功能树)