小言 提出了问题 · 2016-06-21
构造了一个父子树,想获取某个节点的路径,可是获取不了,不知道哪里出错,求解。
var data = [{
'id': 'root',
'text': 'Root',
'children': [{
'id': 1,
'text': 'Child 1'
}, {
'id': 2,
'text': 'Child 2',
'children': [{
'id': 6,
'text': 'Child 6'
}, {
'id': 7,
'text': 'Child 5',
'children': [
]
}]
}]
}];
var tree = function(data) {
this.data = data;
}
tree.prototype = {
init: function(tree, nodeParent) {
var _this = this;
tree = tree || this.data;
if (tree && Array.isArray(tree)) {
tree.forEach(function(node, index) {
node.parent = nodeParent;
if (node.children && Array.isArray(node.children)) {
_this.init(node.children, node);
}
})
}
},
get_path: function(node, path) {
path = path || "";
if (node.parent) {
path = node.text + ' >> ' + path;
this.get_path(node.parent, path);
} else {
return path;
}
console.log(path); // Child 2 >> Child 6 >>
},
// 遍历树
traverse: function(tree, fn) {
var _this = this;
tree = tree || this.data;
if (tree && Array.isArray(tree)) {
tree.forEach(function(node, index) {
fn && fn.call(_this, node, tree, index);
if (node && node.children && Array.isArray(node.children)) {
_this.traverse(node.children, fn);
}
})
} else {
fn.call(_this, tree);
}
},
_get: function(id, fn) {
var _this = this;
var found = false;
this.traverse(this.tree, function(node, tree, index) {
if (node.id === id) {
found = node;
fn && fn.call(_this, node, tree, index);
}
})
if (!found) {
throw new Error("can get node id " + id);
}
return found;
},
};
var mytree = new tree(data);
mytree.init();
console.log(mytree.get_path(mytree._get(6)));
构造了一个父子树,想获取某个节点的路径,可是获取不了,不知道哪里出错,求解。 {代码...}