源代码github地址
下面有在线预览链接,可以用chrome,firefox打开预览。
预览地址
截图:
左边树是我读取一个json文件绘出的,右边树也是读取该文件,使用d3生成,数据经过处理后,添加一些坐标属性。
左侧生成树代码:
$.getJSON("./webstack.json", function(data){
currentNode = data; // currentNode已经在全局定义过了
var str = '<ul>';
selectNode(currentNode);
str += '</ul>';
$(".tree-node").html(str)
function selectNode(node) {
if(node != null) {
str += `<li><span>${node.name}</span> <button class="addChildtree">+</button>`
if(node.children != null && node.children.length != 0 ){
str += `<ul>`
for(var i = 0; i < node.children.length; i++) {
selectNode(node.children[i]);
}
str += `</ul>`
}
str += '</li>'
}
}
});
我的需求是,点击左侧添加时,将新数据添加进当前currentNode
里,然后同步渲染右侧流程图。
我的做法是这样的:
function inserttree(json, currentvalue, newChildTree) {
if(newChildTree != "" && newChildTree != null) {
var currentNode = json;
if(currentNode.name == currentvalue) {
if(currentNode.children instanceof Array) {
currentNode.children.push({"name": newChildTree});
}else {
currentNode.children = [];
currentNode.children.push({"name": newChildTree});
}
}else {
if(currentNode.children != null && currentNode.children.length > 0) {
for(var i = 0; i < currentNode.children.length; i++) {
inserttree(currentNode.children[i], currentvalue, newChildTree);
}
}
}
}
json = currentNode;
}
获取当前点击的节点值currentvalue
和新增值newChildTree
,
通过查询currentvalue
所在位置,然后添加newChildTree
。最终的结果是添加进来了,但是无法把新增的数据复制给完整的currentNode
了。
你的tree的数据模型里自己生成个id吧,这样就能遍历到你修改的currentNode了。