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);
}
})
}
所以我想按如下方式显示类别树: Mobile & Accessories -> Mobiles
手机及配件 -> 充电器
我的 JS fiddle :http://jsfiddle.net/tfa8n5tj/
最佳答案
参见 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
关于javascript - 打印从根节点到叶节点的所有路径 - javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32327815/