In the code above, when you click on an item or subclass, because the event is triggered, the parameters are the same, can distinguish the user clicks in the end is "Project X" or "Subclass X", in addition to this.innerhtml to judge their intrinsic text, can also according to them in order to <ul id= "Demo" > element is the vertical position (node depth) in the XML document of the root node, such as "Project One" in <ul id= "Demo" > The node depth is 2, "subclass one" node depth is 4.
Compute node Depth After the recursive method is excluded, a simpler approach is found:
function Parentindexof (node,parent) {
if (node==parent) {return 0;}
for (var i=0,n=node; n=n.parentnode; i++) {
if (n==p) {return i;}
if (n==document.documentelement) {return-1}//Cannot find the target parent node to prevent a dead loop
}
}
The return value of the function is the index number, if the entry node is the same as the parent node of the lookup (that is, the same element). The return value is 0, after the parent node is rounded up to find the number of nodes to look up, if you look up, to the root node of the entire page, such as
The return value is similar to the IndexOf method built into the string object. The key to the function is for the second parameter N=n.parentnode, which feels more ingenious.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service