打印从根节点到叶节点的所有路径 - javascript

时间:2015-09-01 09:17:54

标签: javascript underscore.js

    function formCategoryTrees(object) {
     _.each(object,function(objectValues){


         var leafCategoryId = objectValues["id"];
         var leafCategoryName =  objectValues["name"];
         console.log(leafCategoryName+""+leafCategoryId );
        if (objectValues.hasOwnProperty("children")) {
            if (typeof objectValues["children"] == 'object')
                 console.log("In");
                formCategoryTrees(objectValues["children"]);
            }else{
console.log(leafCategoryName);
            }

      })

  }

所以我想按如下方式显示类别树:移动&配件 - >手机

移动&配件 - >充电器

我的JS小提琴:http://jsfiddle.net/tfa8n5tj/

2 个答案:

答案 0 :(得分:3)

参见http://jsfiddle.net/sjmcpherso/kc9fehyz/这里我使用递归和放大器创建了一组分层元素。迭代。由于循环中对DOM的操作会极大地影响性能,因此我创建了一个虚拟DOM,并在流程结束时附加到真正的DOM。

var vDOM = document.createDocumentFragment(); //Create a Document Fragment to store your Virtual DOM
function formCategoryTrees(object,par) { //Use the parent node as a parameter to create hierarchy
   var ul = document.createElement('ul');
   _.each(object,function(objectValues ){       
        var li = document.createElement('li');
        var leafCategoryId = objectValues["id"];
        var leafCategoryName =  objectValues["name"]; 
        li.appendChild(document.createTextNode(leafCategoryName + " " + leafCategoryId));

        if(objectValues["children"]) {      
                formCategoryTrees(objectValues["children"],li);
        }
        ul.appendChild(li);

    })    
    par.appendChild(ul);  //Append to the parent node after each iteration
}
formCategoryTrees(object.records,vDOM);
document.body.appendChild(vDOM); //Append your Virtual DOM to your page

答案 1 :(得分:2)

我相信您希望您的功能如下所示:

function formCategoryTrees(object, parentNode) {

    var div = document.getElementById("output");
     _.each(object,function(objectValues){
         var leafCategoryId = objectValues["id"];
         var leafCategoryName =  objectValues["name"];

         if(parentNode === null){
             div.innerHTML = div.innerHTML + leafCategoryName + " " + leafCategoryId +"</br>";
         } else {
             div.innerHTML = div.innerHTML + parentNode + "->" + leafCategoryName + " " + leafCategoryId + "</br>";
         }

         var hasChildren = objectValues.hasOwnProperty("children");
         var childValue = objectValues["children"];

         if(hasChildren && childValue !== null) {
             formCategoryTrees(objectValues["children"], leafCategoryName);
         }

      });
  }

formCategoryTrees(object.records, null);