使用json生成树视图

我想使用jQuery和JSON生成树视图。

我的JSON(单个文件夹):

[{"id":"076ac97d","path":"\/test\/undefined","name":"undefined","parentDirName":"test","parentDirId":"70b77ddd-6c15"}, .... ] 

当文件夹位于root中时,parentDirId键具有空值:“”,如果在目录中,则具有父ID。

我想生成ul li list tree。

你知道如何迭代这个JSON并将ul li列表附加到html吗?

我有一个AJAX:

 $.ajax({ type: "GET", url: ajaxUrl, dataType: "json", contentType: "application/json", success: function(response){ //code } 

如何生成目录树? 首先将dirs附加到带有parentID的dirs。

您可以使用以下function。 它首先创建一个由id键入的新对象结构,允许快速查找每个节点的父节点。 同时,它为每个元素创建一个LI元素,以及一个空的UL元素。 最后,所有这些LIUL元素根据父子关系链接在一起:

 function populateUL($ul, data) { // Register the given UL element as the root in a new data structure var hash = { "": { $ul: $ul } }; // Key the objects by their id, and create individual LI elements for them, // and an empty UL container for their potential child elements data.forEach(function (o) { var $ul = $("
    "); hash[o.id] = { $ul: $ul, $li: $("
  • ").text(o.name).append($ul) }; }); // Append each LI element to the correct parent UL element data.forEach(function (o) { hash[o.parentDirId].$ul.append(hash[o.id].$li); }); } // Sample response object var response = [{ "id":"70b77ddd-6c15", "path":"/test", "name":"test", "parentDirName":"", "parentDirId":"" }, { "id":"076ac97d", "path":"/test/chess", "name":"chess", "parentDirName":"test", "parentDirId":"70b77ddd-6c15" }, { "id":"076ac97e", "path":"/test/bingo", "name":"bingo", "parentDirName":"test", "parentDirId":"70b77ddd-6c15" }, { "id":"076ac97f", "path":"/test/chess/major pieces", "name":"major pieces", "parentDirName":"chess", "parentDirId":"076ac97d" }, { "id":"076ac97g", "path":"/test/chess/major pieces/rook", "name":"rook", "parentDirName":"major pieces", "parentDirId":"076ac97f" }, { "id":"076ac97h", "path":"/test/chess/major pieces/queen", "name":"queen", "parentDirName":"major pieces", "parentDirId":"076ac97f" }, { "id":"076b0000", "path":"/test/chess/minor pieces", "name":"minor pieces", "parentDirName":"chess", "parentDirId":"076ac97d" }, { "id":"076b0001", "path":"/test/chess/minor pieces/knight", "name":"knight", "parentDirName":"minor pieces", "parentDirId":"076b0000" }, { "id":"076b0002", "path":"/test/chess/minor pieces/bishop", "name":"bishop", "parentDirName":"minor pieces", "parentDirId":"076b0000" }]; // Inject response data into document populateUL($("#root"), response);
  

    我猜你的意思是这样的

     function listItem(obj) { var html = "
      " jQuery.each(obj, function(key, value) { html += "
    • " + key + ':' if (typeof value !== "object") html += value else html += listItem(value) html += "
    • " }) return html + "
    " } var obj = { "id": "076ac97d", "rawr": { "mew": 2 }, "path": "\/test\/", "name ": "undefined", "parentDirName ": "test", "parentDirId ": "70 b77ddd " }; document.write(listItem(obj));