zoukankan      html  css  js  c++  java
  • Manually Traverse a DOM Tree Using jQuery | James Wiseman

    Manually Traverse a DOM Tree Using jQuery | James Wiseman

    Example DOM Tree
    Image via Wikipedia

    jQuery does a wonderful job of traversing the DOM tree, so you might ask why you would like to do this yourself?
    I recently encountered a requirement to count the maximum ‘depth’ of a DOM tree. I.e. find the level of the deepest nested element. So, I managed to knock this up in a few minutes:

    1. function Recurse($item, depth) {  
    2.     $item.each(function() {  
    3.         depth.count++;  
    4.         if (depth.count > depth.max) {  
    5.             depth.max = depth.count;  
    6.         }  
    7.         Recurse($(this).children(), depth);  
    8.     });  
    9.     depth.count--;  
    10.     return depth.max;  
    11. }  
    12.   
    13. $(document).ready(function() {  
    14.     alert(Recurse($("body"), { count: 0, max:0 }));  
    15. }  

    A few points to note about this

    • depth is an object with two members, count and max. We want to keep a count of the current and maximum depth, but want to avoid global variables (it’s better practice, and makes the solution more self-contained).
    • JavaScript doesn’t allow us to pass variables by reference. Using the variables within the passed depth object means we can pass values to lower levels of recursion.
    • We must pass an object in our first call. Technically the function can be improved by including a check for this.
    • The function returns depth.max. Although the return value doesn’t matter when the function is called recursively, its useful for passing our intended value out to the original calling function.

    You can test this out on JsFiddle: http://jsfiddle.net/RqHzf/

  • 相关阅读:
    Cf序列化器-Serializer解析
    yield和return
    pymongo的使用
    Homebrew介绍和使用
    TypeError: expected string or bytes-like object
    JavaScript读取文本,并渲染在html
    反序相等
    打印邮票的组合
    打印对称平方数
    字符串按照原意输出
  • 原文地址:https://www.cnblogs.com/lexus/p/2821096.html
Copyright © 2011-2022 走看看