[英]How to store reference of all parents for each of the nested child?
Fiddle : http://jsfiddle.net/p35cobgx/3/ 小提琴: http : //jsfiddle.net/p35cobgx/3/
Below is my tree structure : 下面是我的树结构:
Node
Node-1
Node-1-1......
Now I want to store back reference of all parents for each of the nodes like below : 现在,我想存储每个节点的所有父代的引用,如下所示:
Node 节点
Node-1 (should store back reference of only Node because this is last parent for Node-1) Node-1(应该存储仅Node的引用,因为这是Node-1的最后一个父级)
Node-1-1(should store back reference of all parents ie Node-1 and Node because Node is the last parent for Node-1-1). Node-1-1(应存储所有父节点(即Node-1和Node)的引用,因为Node是Node-1-1的最后一个父节点)。
But problem with my code is i am unable to store reference of Node for Node-1-1 . 但是我的代码存在问题,我无法为Node-1-1存储Node的引用。
I'm not sure if that's exactly the answer you wanted, but here it is: 我不确定这是否正是您想要的答案,但是这里是:
You can access a parent node by using: 您可以使用以下方法访问父节点:
node.parentNode
This is a property and holds the reference for the parent node. 这是一个属性,其中包含父节点的引用。
Also, it's sometimes better to access parent element, instead of node, because whitespace can also be a node, so you can use this property: 另外,有时最好访问父元素而不是节点,因为空格也可以是节点,因此可以使用以下属性:
node.parentElement
The algorithm I would use is to store only the immediate parent in the node. 我将使用的算法是仅将直接父级存储在节点中。
So if A is the parent to B and B of C 因此,如果A是C的B和B的父代
That makes it A->B->C 这使其成为A-> B-> C
C.parent = B; C.parent = B; B.parent = A; B.父母= A;
If I wanted all parents of C, I would do the below 如果我想要C的所有父母,则可以执行以下操作
var parentArray = getParent(C).slice();
this.parents = [];
//use parentArray as you like now!
function getParent(obj){
if(obj.parent){
this.parents.push(obj.parent) //this.parents is an array
getParent(obj.parent);
}else{
return this.parents;
}
}
So if you make a call getParent(C); 因此,如果您调用getParent(C); you get all its parents B and A. If you make a call getParent(B); 如果您打电话给它的所有父母B和A。 you get only A. If you make a call getParent(A); 您只会得到A。如果您调用getParent(A); you get no parents as it doesn't have any parents. 您没有父母,因为它没有父母。
Hope that helps! 希望有帮助!
使用此条件来分配父项:
obj.parent = data.parent || null;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.