2013-10-14 101 views
0
嵌套列表

你好下面是我的JSON,HTML和jQuery代碼示例: JSON:創建使用JSON和jQuery

{ 
"node":[ 
{"name":"XXX", 
"child":[ {"name":"acb"}, 
{"name":"txy"} 
] 
}, 
{"name":"ZZZ", 
"child":[{"name":"ism"}, 
{"name":"sss"} 
] 
}, 
{"name":"PPP"}, 
{"name":"QQQ"} 
] 
} 

jQuery代碼:

$(document).ready(function(){ 
      var $ul=$('<ul></ul>'); 
      $.getJSON('test1.json', function(json) { 
        $.each(json.node, function(key,value){ 
          getList(value, $ul); 
               }) 
              }); 
      $ul.appendTo("body"); 
          }); 
         function getList(item, $list) { 

    if (item) { 
     if (item.name) { 
      $list.append($('<li><a href="#">' + item.name + '</a>' +"</li>")); 
       } 
     if (item.child && item.child.length) { 
      var $sublist = $("<ul/>"); 
      $.each(item.child, function (key, value) { 
       getList(value, $sublist); 
      }); 
      $list.append($sublist); 
     } 
    } 
} 

所以,當我運行這個代碼,列表返回爲

<ul> 
<li></li> 
<ul> 
<li></li> 
<li></li> 
</ul> 
</ul> .. and so on . But i don't want my list to be this was i need it like : 

<ul> 
<li> 
<ul> 
<li></li> 
<li></li> 
</ul> 
</li> 
<li> 
<ul> 
<li></li> 
</ul> 
</li> 
</ul> 

請讓我如何修改我的函數來實現嵌套以這種方式編輯列表!..預先感謝 。

回答

4

嘗試

function getList(item, $list) { 

    if($.isArray(item)){ 
     $.each(item, function (key, value) { 
      getList(value, $list); 
     }); 
     return; 
    } 

    if (item) { 
     var $li = $('<li />'); 
     if (item.name) { 
      $li.append($('<a href="#">' + item.name + '</a>')); 
     } 
     if (item.child && item.child.length) { 
      var $sublist = $("<ul/>"); 
      getList(item.child, $sublist) 
      $li.append($sublist); 
     } 
     $list.append($li) 
    } 
} 

演示:Fiddle