基本上,我根据名称将 ID 添加到节点上的圆圈中:
.append("circle").attr('id', function(d){ return d.name})
然后我填充了所有父母子女姓名的数组,即您要折叠的节点:
if(parentschildren.length<1){ //so it doesn't populate it more than once
node.filter(function(d){
//console.log(d.name)
return d.name === 'PARENT' //return just the parent node
}).each(function(d){
for(i=0;i<d.children.length;i++){
parentschildren.push(d.children[i].name);
}
});
}
然后我使用填充的数组循环选择我想要点击的节点并调用一个点击函数来模拟对选定节点的点击:
function simulateClick(){
$.fn.d3Click = function (i) { //simulate click
//if(i===0){
this.each(function (i, e) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
console.log(e);
e.dispatchEvent(evt);
// nodeEnter.on("click", click)
evt.stopPropagation()
}); //}
};
for(i=0;i<parentschildren.length;i++){ //loop through created array
$('#'+parentschildren[i]).d3Click(); //select element to click
}
}
至于唯一 ID,我会这样做:
node.each(function(d,i){ // use i to iterate through
d.uniqueID = 'uniqueNode' + i;
}
那段代码会给每个人一个唯一的价值。所以第一个将是 uniqueNode1 然后是 uniqueNode2 等等。然后将其应用于您的节点:
nodes.attr('id'(function(d){
return d.uniqueID;
})
至于您的其他问题(我认为您应该将其添加到这个问题中,而不是在 cmets 中,以便人们知道我的答案为何如此之大),这就是答案。
为了让所有节点开始折叠,我使用了递归函数,您已经必须填充一个数组来为您提供具有子节点的节点:
var nodes2 = [];
function flatten(root) {
var nodes = [], i = 0;
function recurse(node) {
if (node.children) {
nodes2.push(node.name) //push the name of the node to the array
node.children.forEach(recurse);
}
if (!node.id) node.id = ++i;
nodes.push(node);
}
recurse(root);
console.log(nodes2)
return nodes;
}
现在,正如我之前所说,我已经根据名称给了它们 id,所以要选择它们,我所要做的就是遍历这个新的节点数组 (nodes2),然后单击与每个节点具有相同 ID 的节点该数组中的元素。但是你不能马上这样做,因为这个数组从最高点(父)开始向下,所以我不得不反转数组:
var newNodes = [];
for(i=nodes2.length; i>=0; i--){
newNodes.push(nodes2[i])
}
现在使用这个数组遍历选择具有相同 ID 的节点:
for(i=0;i<newNodes.length;i++){
if(newNodes[i]){ //check if i isnt undefined etc
$('#'+newNodes[i]).d3Click();
}
}
然后再次单击父级两次(关闭然后打开),如您所愿:
$('#PARENT').d3Click();
$('#PARENT').d3Click();
希望能解决你所有的问题,这里是最终更新的 plnkr:http://plnkr.co/edit/QtFXa53Q7p65NQpO4z5f?p=preview