Title
- Project 1
>Subcategory one-
>Project 1
- , because the triggered events are the same and the parameters are the same, it can distinguish whether the user clicks on "item x" or "subcategory The element is distinguished by the vertical position (node depth) in the xml document where the element is the root node. For example, the node depth of "Project One" in is 2, and the node depth of "Subclass One" is 4.
Calculate the node depth and find a simpler method after excluding the recursive method:
- 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;} //The target parent node cannot be found to prevent an infinite loop - } }
The return value of the function is the index number. If the entry node It is the same as the parent node being searched (that is, the same element), and the return value is 0. After looping upward to find the parent node, the number of nodes searched upward is returned. If the search is upward, the root node of the entire page is reached, such as
, or If it is not found, it returns -1 and ends the loop.
The return value is similar to the built-in indexOf method of String object. The key to the function is the second parameter n=n.parentNode of for, which feels clever.
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn