我有一个d3节点层次结构root-parent-child,我需要输出为ul-li,这样任何有d.depth = max(d.depth)的东西都会成为li元素,并且它们都被ul包裹元素直到d.depth = 0,例如
<ul>
<ul>
<ul>
<li>
<li>
</ul>
</ul>
<ul>
<li>
<li>
</ul>
</ul> ...
我估计我必须以某种方式遍历数据并查看是否有孩子,如果没有附加li,否则追加ul ......但是如何?谢谢!
答案 0 :(得分:2)
你可以这样做:
//here chart is the div on which you want to attach the ul and li.
var myDiv = d3.select('#chart')/
.append("ul")//root ul
.append("li")//root li
.text(data.name)//root li name
.append("ul");//to this add ul
//note i am iterating through the data via recursion.
function makeElements(parentDOM, myData){
myData.children.forEach(function(child){
//add li element
parentDOM.append("li").text(child.name);
//if children then make ul
if (child.children.length > 0){
var ul = parentDOM.append("ul");
//recurse pass ul as parentDOM
makeElements(ul, child);
}
});
}
工作代码here