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/ http://jsfiddle.net/tfa8n5tj/
See http://jsfiddle.net/sjmcpherso/kc9fehyz/ 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)