the data structure is roughly as follows:
data = [
{id: "1",pId: "0",name: "1",
children:[
{id: "10", pId: "1", name: "1",
children:[
{id: "101", pId: "10", name: "1-1",children:[]},
{id: "102", pId: "10", name: "1-2",children:[
{id: "1021", pId: "102", name: "1-2-1",children:[]},
{id: "1022", pId: "102", name: "1-2-2",children:[]}
]}
]
},
{id: "12", pId: "1", name: "2",children:[]},
{id: "13", pId: "1", name: "3",children:[]}
]
},
{id: "2",pId: "0",name: "2",
children:[
{id: "20", pId: "2", name: "1",children:[]},
{id: "22", pId: "2", name: "2",children:[]},
{id: "23", pId: "2", name: "3",children:[]},
{id: "24", pId: "10", name: "4",children:[
{id: "241", pId: "24", name: "4-1",children:[]},
{id: "242", pId: "24", name: "4-2",children:[
{id: "2421", pId: "242", name: "4-2-1",children:[]},
{id: "2422", pId: "242", name: "4-2-2",children:[]}
]}
]}
]
},
{id: "3",pId: "0",name: "3",
children:[
{id: "30", pId: "3", name: "1",children:[]},
{id: "32", pId: "3", name: "2",children:[]},
{id: "33", pId: "3", name: "3",children:[]},
{id: "33", pId: "3", name: "4",children:[]}
]
},
{id: "4",pId: "0",name: "4",
children:[
{id: "40", pId: "4", name: "1",children:[]},
{id: "42", pId: "4", name: "2",children:[]},
{id: "43", pId: "4", name: "3",children:[]}
]
}
]
the dom structure you want to generate is as follows:
<ul id="tree-ul">
<li><a href="-sharp">1 <i class="iconfont icon-expand icon-arr-menu"></i></a>
<ul>
<li><a href="-sharp">1</a></li>
<li><a href="-sharp">2 <i class="iconfont icon-expand icon-arr-menu"></i></a>
<ul>
<li><a href="-sharp-sharp">2-1</a></li>
<li><a href="-sharp">2-2</a></li>
<li><a href="-sharp">2-3</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="-sharp">2 <i class="iconfont icon-expand icon-arr-menu"></i></a>
<ul>
<li><a href="-sharp-sharp">1</a></li>
<li><a href="-sharp">2</a></li>
<li><a href="-sharp">3</a><i class="iconfont icon-expand icon-arr-menu"></i>
<ul>
<li><a href="-sharp-sharp">3-1</a></li>
<li><a href="-sharp">3-2</a></li>
<li><a href="-sharp">3-3</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="-sharp">3 <i class="iconfont icon-expand icon-arr-menu"></i></a>
<ul>
<li><a href="-sharp">1</a></li>
<li><a href="-sharp">2</a></li>
<li><a href="-sharp">3</a></li>
</ul>
</li>
</ul>
how to implement the above structure recursively
there is something wrong with the code written by myself
function menuTree(menu, dt){
for (var i = 0, len = dt.length; i < len; iPP) {
menu += "<li><a data-menuId=""+dt[i].id+"">"+dt[i].name+"<i class="iconfont icon-expand icon-arr-menu"></i></a>";
if(dt[i].children){
menu += "<ul>";
menuTree(menu, dt[i].children);
menu += "</ul>";
}
menu += "</li>";
}
}
var menu = "";
menuTree(menu, data);
$("<ul></ul>").html(menu); // menu